我想使用 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));
}
所有参数的类型都是一样的,所以可以这样写:
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
它在 mingw g++4.5 中编译时出现此错误:
error: no matching function for call to 'maxv(<brace-enclosed initializer list>, <brace-enclosed initializer list>, <brace-enclosed initializer list>)'
因为他不知道{5, 6}
是Point
类型。解决方案是什么?
最佳答案
解决方案是不使用可变参数模板!当与函数模板一起使用时,它们旨在推断参数的类型。这不是您想要做的:您希望参数采用预期的类型。
我没有太多这方面的实践经验,但你会想为此使用初始化列表:
Point maxv(std::initializer_list<Point> list) {
...
}
您可能会提示不能将它用于任意类型,但随后您需要意识到您需要在某处告知涉及的类型。 ...虽然您需要指定参数类型,但它可以成为一个模板。
关于c++ - 具有相同类型参数的类型安全可变参数函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9843567/