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

标签 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));
}

所有参数的类型都是一样的,所以可以这样写:

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/

相关文章:

接受任意数量的回调并存储结果的c++类方法

c++ - 获得向后插入器并回退到任何插入器的惯用方法是什么?

c++ - 等效于嵌套 for 循环的迭代器显示 50% 的性能故障 - 为什么?

qt - QT 折线图中 x 轴上的坐标不正确/自动调整

c++ - 我们如何从 boost::asio::tcp::ip::read_some 调用中顺序接收多个数据?

c++ - 基类函数被调用两次

c++ - 如何让 "Application"项目模板重新出现在 Qt Creator IDE 中?

c++ - 如果我为无符号变量分配负值会发生什么?

visual-studio - 在Visual Studio中创建新项目时没有可用的模板

python - 如果我只想在我的条目下面有一个简单的评论框,我应该使用 Django 的评论框架还是自己编写?