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

为什么'std::function<void()>'接受返回'bool'的lambda而没有任何警告?

  •  0
  • xmllmx  · 技术社区  · 3 年前
    #include <functional>
    
    void f()
    {
        // warning: return-statement with a value, in function returning 'void'
        return true; 
    }
    
    std::function<void()> fn = [] { return true; }; // no warning
    
    int main()
    {}
    

    std::function<void()> 拿一只羔羊回来 bool 没有任何警告?

    2 回复  |  直到 3 年前
        1
  •  2
  •   HolyBlackCat    3 年前

    void

    这是怎么回事 std::is_invocable_r 作品。

    警告 . (与错误失败不同,这很容易。)更不用说标准没有区分警告和错误。

        2
  •  1
  •   Pete Becker    3 年前

    这就是它的工作:它处理所声明的电路类型之间的阻抗匹配 function

    函数的普通指针是严格类型化的:

    int f(double);
    double g(int);
    
    int x = f(3.2); // OK
    long y = f(3);  // OK: argument and return type get converted
    
    int (*ptr)(double);
    ptr = f; // OK: f is pointer to function taking double and returning int
    ptr = g; // error: types don't match
    

    std::function

    std::function<int(double)> func;
    func = f; // OK
    func = g; // OK: argument and return type get converted internally
    

    std::函数