Search code examples
c++templatestypestypeid

Perform different methods based on template variable type


Is there a way to determine the type of variable passed to a template and call a function based on if it's an int or std::string etc...?

For example

template <class T>
struct Jam
{
     Jam(T *var)
     {
         if (typeid(var) == typeid(std::string*)
                *var = "Hello!";
         else if (typeid(var) == typeid(int*)
                *var = 25;
     }
};

When I try to use that code, i get an error invalid conversion from const char* to int. I suspect this is because the compiler "expands" the template into separate functions and when I specified a new instance of the structure throw Jam<std::string>(&setme); it detected the var* = 25 statement and refused to compile.

Is there a proper way to do this? Maybe with macro guards? Thanks.


Solution

  • Use regular function overloading instead:

    template <class T>
    struct Jam
    {
        Jam(std::string* var)
        {
            *var = "Hello!";
        }
    
        Jam(int* var)
        {
            *var = 25;
        }
    };
    

    unless you want to specialize on the type T used to instantiate Jam. In that case you would do:

    template<>
    struct Jam<std::string>
    {
        Jam(std::string* var)
        {
            *var = "Hello!";
        }
    };
    
    template<>
    struct Jam<int>
    {
        Jam(int* var)
        {
            *var = 25;
        }
    };
    
    
    template<typename T>
    struct Jam
    {
        Jam(T* var)
        {
            // every other type
        }
    };