C ++ 11 lambda可以分配给具有不正确签名的std :: function [英] C++11 lambda can be assigned to std::function with incorrect signature

查看:130
本文介绍了C ++ 11 lambda可以分配给具有不正确签名的std :: function的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下编译和运行(在Apple LLVM版本6.1.0和Visual C ++ 2015下):

  #include<功能> 
#include< iostream>

struct s {int x; };

int main(int argc,char ** argv)
{
std :: function< void(s&& f = [](const s& p){std :: cout< p.x; };
f(s {1});
return 0;
}

为什么不赋值 std :: function< ; void(s&&)> f = [](const s& p){std :: cout< p.x; }; 生成错误?接受右值引用的函数不应该具有与接受const左值引用的函数相同的签名,应该是什么?从lambda声明中删除 const 会产生一个预期的错误。

解决方案

要扩展现有的注释和回答:



std :: function< R(A ...)> / code>是它可以包装任何可以用 A ... 调用的函数或函数,并将结果存储在

 <$ c 

$ c> std :: function< int(int)> f = [](long l){return l; };

只是peachy。



你必须问自己什么时候看到这样的东西:如果你有一个lambda采取 const T& ,并且你有一个表达式 T &&&&& (或者,更准确地说,你有一个类型为 T 的xvalue),你可以使用该表达式来调用lambda吗? / p>

可以。



如果可以,然后 std :: function 应该能够存储该函子。这是 std :: function 的主要观点。


The following compiles and runs (under Apple LLVM version 6.1.0 and Visual C++ 2015):

#include <functional>
#include <iostream>

struct s { int x; };

int main(int argc, char **argv)
{
    std::function<void (s &&)> f = [](const s &p) { std::cout << p.x; };
    f(s {1});
    return 0;
}

Why doesn't the assignment std::function<void (s &&)> f = [](const s &p) { std::cout << p.x; }; generate an error? A function accepting an rvalue reference should not have the same signature as a function accepting a const lvalue reference, should it? Dropping the const from the lambda's declaration does generate an error as expected.

解决方案

To expand on the existing comment and answer:

The point of std::function<R(A...)> is that it can wrap any function or functor that can be called with A... and have the result stored in an R.

So, for example,

std::function<int(int)> f = [](long l) { return l; };

is just peachy.

So what you have to ask yourself when you see something like this: if you have a lambda taking const T &, and you have an expression of type T && (or, more accurately, you have an xvalue of type T), can you use that expression to call the lambda?

Yes, you can.

And if you can, then std::function is supposed to be able to store that functor. That's pretty much the main point of std::function.

这篇关于C ++ 11 lambda可以分配给具有不正确签名的std :: function的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆