结构化绑定

当在结构体或者类中使用结构化绑定的时候,需要有公开的访问权限,否则会导致编译失败。这条限制乍看是合理的,但是仔细想来却引入了一个相同条件下代码表现不一致的问题:

cpp 复制代码
struct A 
{
    friend void foo();
private:
    int i;
};

void foo() 
{
    A a{};
    auto x = a.i; // 编译成功
    auto [y] = a; // 编译失败
}

在上面这段代码中,foo是结构体A的友元函数,它可以访问A的私有成员i。但是,结构化绑定却失败了,这就明显不合理了。同样的问题还有访问自身成员的时候:

cpp 复制代码
class C 
{
    int i;
    void foo(const C& other) 
    {
        auto [x] = other; // 编译失败
    }
};

为了解决这类问题,C++20标准规定结构化绑定的限制不再强调必须为公开数据成员,编译器会根据当前操作的上下文来判断是否允许结构化绑定。幸运的是,虽然标准是2018年提出修改的,但在我实验的3种编译器上,无论是C++17还是C++20标准,以上代码都可以顺利地通过编译。

在C++20之前,lambda不能直接捕获结构化绑定的变量的

cpp 复制代码
#include <iostream>
#include <map>

using UeIdDu = int;
using UeCtx = int; //same as ueContext
std::map<UeIdDu, UeCtx> ueIds{{1, 10}, {2, 20}, {3, 30}};

int main()
{
        //solution 1
        for (const auto& [ueIdDu, ueCtx] : ueIds)
        {
	    const auto& ueId = ueIdDu; 
	    const auto& ctx = ueCtx; //sometime variable name is not good
	    [ueId, &ctx]() //C++ 17
	    {
	        std::cout << "ueIdDu: " << ueId << ", ueCtx: " << ctx << std::endl;
	    }();
	}
	//solution 2
	for (const auto& [ueIdDu, ueCtx] : ueIds)
	{
	    [ueIdDu = ueIdDu, &ueCtx = ueCtx]() //C++17
	    {
	        std::cout << "ueIdDu: " << ueIdDu << ", ueCtx: " << ueIdDu << std::endl;
	    }();
	}

    return 0;
}

c++20开始lambda可以捕获结构化绑定变量了:

cpp 复制代码
#include <iostream>
#include <map>

using UeIdDu = int;
using UeCtx = int;//same as ueContext

std::map<UeIdDu, UeCtx> ueIds{{1, 10}, {2, 20}, {3, 30}};

int main()
{
          //structure binding ueIdDu and ueCtx
	for (const auto& [ueIdDu, ueCtx] : ueIds)
	{
	    [ueIdDu, &ueCtx]()  //OK since C++20, C++17 clang failed!
	    {
	        std::cout << "ueIdDu: " << ueIdDu <<
                 ", ueCtx: " << ueCtx << std::endl;
	    }();
	}

    return 0;
}
相关推荐
一丝晨光11 小时前
继承、Lambda、Objective-C和Swift
开发语言·macos·ios·objective-c·swift·继承·lambda
钗头风6 天前
(一)Lambda-Stream流
java·lambda
wumingxiaoyao15 天前
AWS 实时数据流服务 Kinesis
云计算·big data·aws·lambda·kinesis
怒码ing1 个月前
浅谈维度建模、数据分析模型,何为数据仓库,与数据库的区别
大数据·数据仓库·实时数仓·lambda·数据湖·离线数仓·kappa
wumingxiaoyao1 个月前
AWS 无服务计算服务 Lambda
云计算·aws·lambda·sqs·cloudformation
_whitepure3 个月前
Java中常见的语法糖
java·枚举·lambda·泛型·内部类·java语法糖·自动拆箱装箱
opensnn3 个月前
Java8的Lambda表达式
java·lambda
亿牛云爬虫专家4 个月前
在Visual Studio Code中使用pytest进行AWS Lambda函数测试的最佳实践
vscode·pytest·爬虫代理·aws·visual studio code·lambda·代理ip
麻辣韭菜4 个月前
C++ 11 【可变参数模板】【lambda】
c++11·lambda·可变参数模板
清风絮柳4 个月前
Lambda 表达式练习
java·lambda