I’m trying to write a c++ template method.
Below is a sample code demonstrating what I want to do within the method.
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;
}
Basically, the behavior (the string value in this example) of the method will change based on the type T.
How could I do this with template?
You can specialize your template over different types. If you start with a base case:
You can then declare different behavior for any specific value of
T:And so forth. But since only the input type of your function is changing, you really don’t need templates in this case! You can just overload your function with different argument types:
EDIT: Using template specialization to get the name of a type and use it in another function template:
Of course, you can still do this without templates:
If you had to do some complex type-level computation, I’d suggest using templates. But here, I think you can accomplish what you want rather nicely without them. Either way, the idiomatic way (with or without templates) is to split your function into its different natural pieces.