为什么相同类型的lambda参数无法推论为模板参数?

时间:2018-11-27 22:32:06

标签: c++ templates

下面的示例看起来很奇怪而且毫无意义,但是它会产生与我在其他地方实际遇到的错误相同的错误。

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

错误是

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&)>’)

如果我将Lambda放入可解决问题的std::function

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

我也可以这样解决它。

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

基于此修复程序的工作,我认为它最初失败了,因为两个编译器无法确定参数F&aF&b实际上具有相同的类型。但是它们确实具有相同的类型。

我很困惑。为什么第一个版本不起作用?

0 个答案:

没有答案
相关问题