Search code examples
c++templates

C++ - what type to supply for explicit instantiation of a template function, when std::less is one of the arguments?


eg. Function header is:

template <class comparison_function, class iterator_type, class size_type>
bool F(comparison_function compare, iterator_type it)

Call takes iterator_type and comparison_function parameters, but not size_type. Hence the function call has to be explicit eg.:

F<?, std::vector<int>::iterator, long int>(std::less<int>(), it);

What would ? be?


Solution

  • What would ? be?

    It should be the type of the first passed argument i.e., std::less<int>

    //vvvvvvvvvvvvvv----------------------------------------vvvvvvvvvvvvvv
    F<std::less<int>, std::vector<int>::iterator, long int>(std::less<int>(), it);
    

    Note that the parenthesis () in std::less<int>() means that you're passing a default constructed object of type std::less<int>.


    Sidenote

    You can avoid passing two of the template arguments explicitly by making use of template argument deduction. This can be done by making size_type to be the first template parameter so that the remaining two template parameters can be deduced from the passed arguments as shown below:

    //--------vvvvvvvvvvvvvvv--------------------------->now size_type is the first template parameter
    template <class size_type, class comparison_function, class iterator_type>
    void F(comparison_function compare, iterator_type it);
    
    int main()
    {
    //----------vvvvvvvvvvvvvvvvvvvv---->this uses template argument deduction for the remaining two parameters 
        F<long>(std::less<int>(), it);
    }