Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 709
user99545 Avatar asked Jun 13 '12 18:06

user99545


2 Answers

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
    }
};
like image 153
K-ballo Avatar answered Oct 16 '22 07:10

K-ballo


Look up "partial template specialization".

Take Jam()'s body out of Jam{}:

template <class T>
struct Jam
{
  Jam(T *var);
};

Now write two bodies:

Jam<int>::Jam(int *var) {
   // stuff
}

Jam<std::string>::Jam(std::string *var) {
   // stuff
}

(Warning: Rusty C++. But that's generally how you do it.)

New question: If you need duck-typing, why are you using C++ at all? I'd switch to Ruby, and save the C++ for plugins that need speed. But C++ will still support elegant designs, with more work!

like image 32
Phlip Avatar answered Oct 16 '22 07:10

Phlip