Type-safe variational functions with parameters of the same type

I want to use multidirectional variational functions introduced in C ++ 11, but not with different types. Example:

template<typename T>
T maxv(T first, T second) {
  return first > second ? first : second; 
}

template<typename T, typename ... Rest>
T maxv(T first, T second, T ... rest) {
  return maxv(first, maxv(second, rest));
}

The type of all parameters is the same, so it's possible to write something like this:

struct Point { int x,y; };  

template<>
Point maxv(Point first, Point second) {
  return first.x > second.x ? first : second; 
}  

maxv({1, 2}, {3, 4});         // no problem    
maxv({1, 2}, {3, 4}, {5, 6}); // compile error

It compiles with this error in mingw g ++ 4.5:

error: no matching function for call to 'maxv(<brace-enclosed initializer list>, <brace-enclosed initializer list>, <brace-enclosed initializer list>)'

Because he does not know what {5, 6}type is Point. What is the solution?

+5
source share
1 answer

The solution is not for using variable templates! When used with function templates, they are designed to output argument types. This is not what you want to do: you want the arguments to take the expected type.

, :

Point maxv(std::initializer_list<Point> list) {
    ...
}

, , , , .... , .

+10

All Articles