函数对象作为模板参数

Function object as template parameter

本文关键字:参数 对象 函数      更新时间:2023-10-16
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)