TL;DR
How do I initialize a static template variable that will have a different value for each class that inherits from it?
Not TL;DR
I have the following code in my project, that is intended to identify the class created with a template parameter, to make sure no one else creates it (in a different part of the code, not represented here):
template <typename T>
class foo
{
... some other code and methods ...
virtual const char* getId()
{
return idString;
}
static const char* const idString;
};
I would like to initialize idString, so as we know and saw here and here, I want to initialize the variable in the header file underneath the class definition, where the above class declaration is located:
template <typename T>
const char* const idString = strcat("foo::", #T);
or something like that, because this does not compile. This is done so that the following code:
class bar : public foo<S>
{
...some other code...
const char* getId()
{
return idString;
}
static const char* const idString;
};
will generate "foo<S>"
when getId()
is called with a bar
class instance and "foo<T>"
when the base class getId()
is called, by hiding the const variable idString
of foo
(this is, of course, not an override).
Thing is, strcat
is not a something the compiler can calculate at run time, so this doesn't work well. Currently, the only thing that will work, but has backward compatibility issues is adding a const char*
class parameter to the foo
class definition, but than each instance of foo<P>
will have to beconme foo<P, "foo::P">
manually, and will break previous code uses.
I have read a few solutions that looked like this which rely on RTTI, but this isn't the case here.
Thought of using a macro
for this, since macros are pre-compilation and can "know" the string representation from the text written, but can't get the syntax properly. Any other suggestions will be incredible! Thank you.
``` because ```"foo::p"``` is not valid parameter for the template and string literals can never be used for this purpose .
– newbie Apr 07 '21 at 06:00