How to refer from a not-yet-defined symbol from template class?

Viewed 55

I was thinking naively that inside template class I can refer to non-existing objects because they are not necessary before instantiation. But this doesn't work (compiler complains about non-declared NAME):

template<typename H>
class HandlerInfoClass
{
    std::string_view getName()
    {
        return NAME;
    }
};

Is there any way to overcome this without using the preprocessor or adding new template arguments (some of them may have types not allowed in this context)?

2 Answers

No it is not possible to refer to a non-existing object. A key property of a template function is that the output is always the same for given parameter(s). So it doesn't matter where you instantiate the template in your code, it will always call the same function for the same parameters.

What you are building looks like a trait class for a "handler". The correct way to write this would be to specialize the class for each different type like so:

template<typename H>
class HandlerInfoClass;

template<>
class HandlerInfoClass<HandlerType>
{
    static std::string_view getName()
    {
        return "HandlerType";
    }
};

If the string you are returning changes at runtime you shouldn't be building a traits class but add a getName() function to the object itself.

Thanks to G.M. I found a nice workaround: put "NAME" as static variable into type that is template parameter:

template<typename H>
class HandlerInfoClass
{
    std::string_view getName()
    {
        return H::NAME;
    }
};
Related