سؤال

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.

هل كانت مفيدة؟

المحلول

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
    }
};

نصائح أخرى

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!

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top