结构化绑定

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

struct A 
{
    friend void foo();
private:
    int i;
};

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

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

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

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

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

#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可以捕获结构化绑定变量了:

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

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值