简体   繁体   中英

default value for template function, functional parameter

template<typename Iterator, typename typename Comparator = std::less<typename std::iterator_traits<Iterator>::value_type>>
static void sort(Iterator begin, Iterator end, Comparator cmp = Comparator())
{
    ...
}

I have the following template function:

template<typename func>
static void sort_test(func sort)
{
    ...
    sort(somevector.begin(), somevector.end());
    ...
}

int main()
{
    sort_test(&sort<vector<int, allocator<int>>::iterator>);
    return 0;
}

error C2198: 'void (__cdecl *)(iterator,iterator,std::less)' : too few arguments for call

If I try to bypass the default argument by providing it:

template<typename func>
static void sort_test(func sort)
{
    ...
    sort(somevector.begin(), somevector.end(), std::less<int>);
    ...
}

int main()
{
    sort_test(&sort<vector<int, allocator<int>>::iterator>,
                    std::less<int>);
    return 0;
}

error C2275: 'std::less' : illegal use of this type as an expression

Default arguments are not part of a function's signature, so when you go through a pointer to function indirection, as you're doing in the first example, that information is lost. If you call your sort function directly within main with 2 iterator arguments, the code will compile.

In the second example you're getting a compilation error because you're trying to pass a type, instead of an instance, to sort

sort(somevector.begin(), somevector.end(), std::less<int>());

You also have an extra typename in the template parameter list for sort

template<typename Iterator, typename typename Comparator = std::less<typename std::iterator_traits<Iterator>::value_type>>
//                          ^^^^^^^^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM