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:
unless you want to specialize on the type
Tused to instantiateJam. In that case you would do: