Getting template parameter as stringhttp://forum.devmaster.net/t/getting-template-parameter-as-string/12143
Hi guys,
I'm having a little trouble ...
Basically what I'd like to do is that a class template should return one of its parameters as a string like this:
#define ToStr(val) #val
template <class T>
cTest
{
T* mT;
//..some stuff using mT
char* GetName()
{
return ToStr(T);
}
};
This compiles but GetName() returns "T", not the actual parameter.
I tried to pass the parameter name as another template parameter:
template <class T,char* NAME=ToStr(T)>
...
This doesn't compile because:
"invalid expression as a template argument for NAME".
It won't compile for anything I tried but a NULL ptr.
SO what's the way to do this??
Thx,
ALex
Fri, 16 Mar 2007 16:13:35 +0000general devGetting template parameter as string@oisyn wrote:

Oh my bad, MyString isn't seen as being external if it's just const. It works if you drop the 'const' of MyString -or- if you define it as being external:

I haven't found a way to declare an array so that it is accepted as template argument.

@_dave

I wanted to avoid adding the GetName() function to each class as these are very generic classes used as events and as interface handler. So I have tons of instances that would require adding the function.

As for rtti,..well I kinda dislike enabling it for this single small thingy..I don't need it anywhere else.

The first way doesn't work because the preprocessor (which is what handles #defines) works before the actual compiler even starts. So ToStr(T) gets substituted with "T" regardless of T's status as a template parameter or anything else.

The second way doesn't work because template parameters are only allowed to be typenames and enumerable types (basically, ints). This is because the compiler generates a new copy of the template for each combination of parameters. If things like pointers or floats were allowed, it would be extremely easy to accidentally create an enormous number of copies of the template.