I have a function template which is called with different values, i.e.
template <typename T>
T do_calculations(const T &var)
{
T return_variable;
//Do calculations
return return_variable;
}
Now the calculations depend on the type of the variable var
. T
can either be a scalar (such as double
or int
), a vector (such as std::vector<>
or other types) or a matrix. I know that I can differentiate between for example a std::vector
and a double
by knowing that double
does not have a member function called size()
. How can I implement that in my code above? My aim is to have similar code to this:
template <typename T>
T do_calculations(const T &var)
{
T return_variable;
if(T.has_function_size())
//Do calculations on vector
else
//Do calculations on scalar
return return_variable;
}
I can not do a simple check if T
is a known type due to having a lot of different input types, but I know that all possible types having a function size()
behave similar enough for me.
Now my problem is:
My code for the vector calculation loops over all elements, but the code for scalar calculation only over the single element:
template <typename T>
T do_calculations(const T &var)
{
T return_variable;
if(T.has_function_size())
for(size_t i = 0; i < T.size(); ++i)
return_variable[i] = func(var[i]);
else
return_variable = func(var);
return return_variable;
}
with func()
a function taking a scalar.
Compilation fails with the error that I can not apply func()
to a vector (or my own type). Do I have to create separate functions for that, or can I tell the compiler that I know what I do?