具有相同类型参数的类型安全可变参数函数

R1t*_*chY 6 c++ templates c++11

我想使用C++ 11中引入的类型安全的可变参数函数,但不是使用不同的类型.一个例子:

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));
}
Run Code Online (Sandbox Code Playgroud)

所有参数的类型都是相同的,因此可以编写类似的东西:

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
Run Code Online (Sandbox Code Playgroud)

它在mingw g ++ 4.5中编译了这个错误:

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

因为他不知道那种{5, 6}类型Point.解决办法是什么?

Die*_*ühl 11

解决方案是使用可变参数模板!与函数模板一起使用时,它们旨在推断出参数的类型.这不是你想要做的:你希望参数采用预期的类型.

我没有很多实际经验,但你想使用初始化列表:

Point maxv(std::initializer_list<Point> list) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

你可能会抱怨你不能在任意类型中使用它,但是你需要意识到你需要告诉某个地方涉及什么类型....虽然您需要指定参数类型,但它可以成为模板.