0

The below example looks strange and pointless, but it produces what I believe to be the same error that I'm actually experiencing elsewhere.

template <typename T, typename F>
bool foo (const T & x, const F & a, const F & b)
{
    return a (x) == b (x);
}

template <typename T>
bool bar (const T & x, const T & a, const T & b)
{
    return foo (
        x,
        [&] (const T & arg) {return a == arg;},
        [&] (const T & arg) {return b == arg;});
}

int main ()
{
    bar (0, 0, 0);
}

The error is

no matching function for call to ‘foo(const int&, bar(const T&, const T&, const T&) [with T = int]::<lambda(const int&)>, bar(const T&, const T&, const T&) [with T = int]::<lambda(const int&)>)’

deduced conflicting types for parameter ‘const F’ (‘bar(const T&, const T&, const T&) [with T = int]::<lambda(const int&)>’ and ‘bar(const T&, const T&, const T&) [with T = int]::<lambda(const int&)>’)

If I put the lambdas into std::function that fixes the problem

std::function<bool(int)> f_a = [&] (const T & arg) {return a == arg;};
std::function<bool(int)> f_b = [&] (const T & arg) {return b == arg;};

return foo (x, f_a, f_b);

I can also fix it like this.

template <typename T, typename F1, typename F2>
bool foo (const T & x, const F1 & a, const F2 & b)

Based on this fix working, I assume it failed initially because the two compile could not determine that the arguments F&a and F&b actually have the same type. But they do have the same type.

I'm confused. Why doesn't the first version work?

spraff
  • 32,570
  • 22
  • 121
  • 229
  • These lambdas are not identically typed. Why did you assume they were? – AnT stands with Russia Nov 27 '18 at 22:35
  • The type of the lambda is unspecified, usually a different type for each lambda expression you type. You should use two different template parameters if you have two function parameters – pqnet Nov 28 '18 at 00:52
  • @AnT because they have the same signature. If this wasn't the case I don't see how std::function could reasonably be implemented. – spraff Nov 28 '18 at 11:32

0 Answers0