1
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;};

That's an example from Essential c++. Comp is obviously a function object class name. Why could I use the Comp(val, _val) directly? Normally I think I should firstly define a function object like this: Comp comp, then invoke comp not Comp.

4

1 回答 1

1

原样编译的代码是因为模板成员仅在实例化时才检查语义正确性。不过,代码在语法上是格式良好的。但是,当您尝试实例化 的函数调用运算符时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)
于 2015-11-04T19:56:42.770 回答