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; } 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; } 模板 内联常数T最佳频率2(常数T&lhs、常数T&rhs、Pred p=std::less()) { 返回p(左侧、右侧)?左侧:右侧; }

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; } 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; } 模板 内联常数T最佳频率2(常数T&lhs、常数T&rhs、Pred p=std::less()) { 返回p(左侧、右侧)?左侧:右侧; },c++,C++,但是当我调用BestOfTwo(3,5)时,这没有起作用。编译器告诉我没有重载的实例匹配。所以现在我必须这样写: 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; } template <type

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

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;
}
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;
}
模板
内联常数T最佳频率(常数T&lhs、常数T&rhs、Pred p=Pred())
{
返回p(左侧、右侧)?左侧:右侧;
}

当我调用BestOfTwo(3,5)时,这一点没有出错。但我认为前一种风格更方便,我不知道哪里出了问题。有什么建议吗?

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

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

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);
}
模板
内联常数T最佳频率(常数T&lhs、常数T&rhs、Pred p=Pred())
{
//
}
模板
内联常数T最佳频率2(常数T和lhs、常数T和rhs)
{
返回两个最佳频率(左、右);
}

如果您明确指定了模板参数,则第一个版本可以工作:

BestOfTwo<int, std::less<int>>(3, 5)
BestOfTwo(3,5)
原因是默认函数参数不能用于推断模板参数的类型。

可能重复。