1

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?

arc_lupus
  • 3,942
  • 5
  • 45
  • 81
  • 1
    This could answer your question https://stackoverflow.com/questions/257288/is-it-possible-to-write-a-template-to-check-for-a-functions-existence – JomsDev Aug 07 '17 at 10:54
  • @JomsDev: Unfortunately not fully, I expanded the question. – arc_lupus Aug 07 '17 at 13:09
  • 2
    It is preferred if you can post separate questions instead of combining your questions into one. That way, it helps the people answering your question and also others hunting for at least one of your questions. Thanks! – Toby Speight Aug 07 '17 at 13:55

0 Answers0