模板中不允许使用 C++ 默认参数?

标签 c++

在我的 C++ 代码中,我是这样写的:

template <typename T, typename Pred>
inline const T BestOfTwo(const T& lhs, const T& rhs, Pred p = std::less<T>())
{
    return p(lhs, rhs) ? lhs : rhs;
}

但是当我调用 BestOfTwo(3, 5) 时,这不起作用。编译器告诉我没有匹配的重载实例。所以现在我必须这样写:

template <typename T, typename Pred = std::less<T> >
inline const T BestOfTwo(const T& lhs, const T& rhs, Pred p = Pred())
{
    return p(lhs, rhs) ? lhs : rhs;
}

当我调用 BestOfTwo(3, 5) 时,这可以正常工作。但我觉得以前的风格更方便,我没有弄清楚哪里出错了。有什么建议?

最佳答案

只有第二个版本是正确的(如果您不想手动指定 Pred 参数),但仅从 C++11 开始。 Angew 已经给出了一个答案,阐明了为什么第一个版本不正确,没有指定 Pred 参数。

如果你不能使用 C++11,你应该编写两个重载(一个使用 Pred,一个没有,使用 std::less),因为默认模板参数在 C++98 中明确禁止 for 函数模板。

template<typename T, typename Pred>
inline const T BestOfTwo(const T& lhs, const T& rhs, Pred p = Pred())
{
   //
}

template<typename T>
inline const T BestOfTwo(const T& lhs, const T& rhs)
{
   return BestOfTwo<T, std::less<T> >(lhs, rhs);
}

关于模板中不允许使用 C++ 默认参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27605114/

相关文章:

c++ - 调用 GetWindowRect 时出现编译器错误

c++ - 单个目标的 Makefile 多个依赖行?

c++ - 如何将 char 字符显示为 int,而不是 ASCII 符号

php - 从 C 执行 php 脚本

c++ - Cygwin 的 cmake 与 CMAKE_SYSTEM_NAME 不匹配

c++ - 简单的 VBO 不显示

c++ - 表达式树的现代 C++ 版本 https ://gist. github.com/2934374

c++ - cmake 不会编译为 C++ 11 标准

c++ - extconf.rb:如何生成依赖于头文件更改的 makefile 目标?

c++ - 标准库字符串的 placement new 内存泄漏