代码之家  ›  专栏  ›  技术社区  ›  spraff

为什么相同类型的lambda参数不能推断为模板参数?[重复]

  •  0
  • spraff  · 技术社区  · 6 年前

    下面的例子看起来很奇怪,毫无意义,但它产生了我认为与我在其他地方实际经历的错误相同的错误。

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

    如果我把羊肉放进 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&a F&b 实际上是同一类型的。但它们的类型是一样的。

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

    0 回复  |  直到 6 年前