I'd like to write a templated function which changes its behavior depending on template class types passed in. To do this, I'd like to determine the type passed in. For example, something like this:
template <class T>
void foo() {
if (T == int) {开发者_运维知识库 // Sadly, this sort of comparison doesn't work
printf("Template parameter was int\n");
} else if (T == char) {
printf("Template parameter was char\n");
}
}
Is this possible?
This is the purpose of template specialization, a search for that term gives tons of examples.
#include <iostream>
template <typename T>
void foo()
{
std::cout << "Unknown type " << typeid(T).name() << "\n";
}
template<typename T>
void fooT(T const& x) { foo<T>(); }
template<>
void foo<int>()
{ printf("Template parameter was int\n");
}
template<>
void foo<char>()
{ printf("Template parameter was char\n");
}
int main()
{
fooT(std::cout);
fooT(5);
fooT('a');
fooT("Look Here");
}
By using the power of partial specialization, this can be done at compile time:
template<class T, class U>
struct is_same_type
{
static const bool value = false;
};
template<class T>
struct is_same_type<T, T>
{
static const bool value = true;
};
template <class T>
void foo()
{
if (is_same_type<T, int>::value)
{
printf("Template parameter was int\n");
}
else if (is_same_type<T, char>::value)
{
printf("Template parameter was char\n");
}
}
Compiled in my head, but should work nonetheless.
Using template specialization or typeid would probably work for you, although you might prefer template specialization as it won't incur the runtime cost of typeid. For example:
#include <iostream>
#include <typeinfo>
template <typename T>
void foo(T arg) {
if (typeid(arg) == typeid(int)) std::cout << "foo<T> where T is int\n";
else if (typeid(arg) == typeid(double)) std::cout << "foo<T> where T is double\n";
else if (typeid(arg) == typeid(char)) std::cout << "foo<T> where T is char\n";
}
template <>
void foo<int>(int arg) {
std::cout << "foo<int>\n";
}
int main() {
foo(3); // foo<int>
foo(3.0); // foo<T> where T is double
foo('c'); // foo<T> where T is char
}
Use type_info directly, or better still typeid operator to do that.
#include <typeinfo>
template < typename T >
T max( T arg1, T arg2 ) {
cout << typeid( T ).name() << "s compared." << endl;
return ( arg1 > arg2 ? arg1 : arg2 );
}
精彩评论