在我的 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/