C++模板方法,根据模板类改变行为

Neo*_*cer 2 c++ templates

我正在尝试编写一个c ++模板方法.下面是一个示例代码,演示了我想在方法中做什么.

template<class T>
void method(T value) {
    // This string should change based on type T 
    char *str = "Int" or "Float" or .. ;   
    ...
    ...
    std::cout << value << " is of type " << str << std::cout;
}
Run Code Online (Sandbox Code Playgroud)

基本上,方法的行为(本例中的字符串值)将根据类型T进行更改.如何使用模板执行此操作?

Jon*_*ing 11

您可以在不同类型上专门化您的模板.如果你从基础案例开始:

template <class T>
void method(T value);
Run Code Online (Sandbox Code Playgroud)

然后,您可以为以下任何特定值声明不同的行为T:

template <>
void method<int>(int value) {
  // special behavior
}
Run Code Online (Sandbox Code Playgroud)

等等.但由于只有函数的输入类型发生了变化,所以在这种情况下你真的不需要模板!您可以使用不同的参数类型重载您的函数:

void method(int T);
void method(float T);
void method(void* T);
Run Code Online (Sandbox Code Playgroud)

编辑:使用模板特化来获取类型的名称并在另一个函数模板中使用它:

template <class T>
std::string type_to_string();

template <>
std::string type_to_string<int>() {
  return "int";
}

template <>
std::string type_to_string<float>() {
  return "float";
}


template <class T>
some_other_function(T value) {
  std::cout << value << " is a " << type_to_string<T>() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

当然,你仍然可以在没有模板的情况下这样做:

std::string type_to_string(int) {
  return "int";
}

some_other_function(int value) {
  std::cout << value << " is a " << type_to_string(value) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

如果你不得不做一些复杂的类型级计算,我建议使用模板.但在这里,我认为如果没有它们,你可以很好地完成你想要的东西.无论哪种方式,惯用方式(有或没有模板)是将您的功能分成不同的自然部分.