Search code examples
c++function-object

Function object as template parameter


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.


Solution

  • The code as is compiles because the template members are only checked for semantic correctness when they are instantiated. The code is syntactically well-formed, though. However, when you try to instantiate the function call operator of LessThanPred<T>, you'll get a compiler error. For example, with the version of clang (3.6.1) I'm using I get

    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);
    

    when trying to use the function as

    LessThanPred<int>(2)(1)