Is it possible to cout what kind of type a template is? The following code obviously doesn't work, but something alone these lines?
Code:template <typename T>
void showType()
{
cout << T << endl;
}
Printable View
Is it possible to cout what kind of type a template is? The following code obviously doesn't work, but something alone these lines?
Code:template <typename T>
void showType()
{
cout << T << endl;
}
I believe you can use typeid.
just make sure you enable RTTI first.
if you don't want to do that, you can use some template specialisation trickery.
obviously that's a lot of work, but you can add showType specialisations when you define a new type.Code:template <typename T>
void showType(); // don't define this
template <>
void showType<int>()
{
cout << "int" << endl;
}
template <>
void showType<float>()
{
cout << "float" << endl;
}
template <>
void showType<char>()
{
cout << "char" << endl;
}
template <>
void showType<MyClass>()
{
cout << "MyClass" << endl;
}
It's easier to use RTTI, but some people don't like it.
What I ened up doing is:
Works great for what I need.Code:template <typename T>
void showType()
{
cout << typeid(T).name() << endl;
}
Thanks,
Matt
But may not have the desirable effect on other compilers. Keep in mind the result of name() is implementation dependent and the resulting string may not fit into your needs.
If however, you don't plan to make this portable across different compilers, it shouldn't make much of a difference.
Hmmm Well I am developing in VS 2005, Windows XP.... But this will also need to work under SUSE 10.1, with the gcc compiler.
Any Known issues with name() there?
It doesn't necessarily return a very user-friendly value, and the value it does return will be different if you move platforms. But for any one particular platform the name will be consistent.