gpt4 book ai didi

c++ - 函数对象作为模板参数

转载 作者:行者123 更新时间:2023-11-30 05:36:32 24 4
gpt4 key购买 nike

template <typename elemType, typename Comp = less<elemType> >
class LessThanPred {
public:
LessThanPred(const elemType &val) : _val(val){}
bool operator()(const elemType &val) const
{ return Comp(val, _val); }
void val(const elemType &newval) { _val = newval; }
elemType val() const { return _val; }
private:
elemType _val;};

这是来自 Essential c++ 的示例。 Comp 显然是一个函数对象类名。为什么我可以直接使用 Comp(val, _val)?通常我认为我应该首先像这样定义一个函数对象:Comp comp,然后调用 comp 而不是 Comp

最佳答案

代码按原样编译,因为模板成员仅在实例化时检查语义正确性。不过,该代码在语法上结构良好。但是,当您尝试实例化 LessThanPred<T> 的函数调用运算符时,你会得到一个编译器错误。例如,版本为 clang (3.6.1) 我用我得到

less-than.cpp:8:18: error: no matching constructor for initialization of 'std::less<int>'
{ return Comp(val, _val); }
^ ~~~~~~~~~
less-than.cpp:17:25: note: in instantiation of member function 'LessThanPred<int, std::less<int> >::operator()' requested here
LessThanPred<int>(2)(1);

尝试将函数用作

LessThanPred<int>(2)(1)

关于c++ - 函数对象作为模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33530674/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com