Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enabling automatic deduction of template argument type based on that argument's default value

Here's what I want to do:

#include <vector>

template <class ContainerType, typename ComparatorType>
void f(
    ContainerType c1,
    ComparatorType comp = 
    [](const typename ContainerType::value_type& l, const typename ContainerType::value_type& r) {return l < r;})
{
}

int main()
{
    std::vector<int> a{1, 2};
    f(a);
    return 0;
}

But it doesn't work: could not deduce template argument for 'ComparatorType'.

Using a proxy function instead of an actual default argument value works, but seems overly verbose, isn't there a better way? Not to mention it's not the same since now I can't just substitute the default comparator with my own without changing the function name in the client code.

#include <vector>

template <class ContainerType, typename ComparatorType>
void f(
    ContainerType c1,
    ComparatorType comp)
{
}

template <class ContainerType>
void f2(ContainerType c)
{
    f(c, [](const typename ContainerType::value_type& l, const typename ContainerType::value_type& r) {return l < r;});
}

int main()
{
    std::vector<int> a{1, 2};
    f2(a);
    return 0;
}
like image 908
Violet Giraffe Avatar asked Jan 01 '23 01:01

Violet Giraffe


1 Answers

without changing the function name in the client code.

You can overload function templates just fine. There is no need to use a different name.

template <class ContainerType, typename ComparatorType>
void f(
    ContainerType c1,
    ComparatorType comp)
{
}

template <class ContainerType>
void f(ContainerType c)
{
    f(c, [](const typename ContainerType::value_type& l, const typename ContainerType::value_type& r) {return l < r;});
}

You can't make a default function argument contribute to template argument deduction. It's not allowed because it raises some difficult to resolve questions in the deduction process.

like image 153
StoryTeller - Unslander Monica Avatar answered Jan 13 '23 11:01

StoryTeller - Unslander Monica