C++lambda表达式的类型

运算符重载

参考:https://en.cppreference.com/w/cpp/language/operators

如上参考链接,运算符重载大致有这样几种:
在这里插入图片描述
其中 operator type 有些特殊,涉及到转换函数,不需要加 return type,见下。

转换函数

见我的笔记:https://blog.csdn.net/weixin_47652005/article/details/118856689

简单测试例子:

#include <iostream>

class Conv2int
{
public:
	operator int() const
	{
		return 10;
	}
};

int main()
{
	Conv2int my_int;
	std::cout << my_int * 5 << std::endl;
}

不带 captures 的 lambda

通过网站:https://cppinsights.io/

在这里插入图片描述
简单的测试:

#include <iostream>

int main()
{
 	auto f = [](int a){std::cout << a << std::endl; return a;};
}

结果:

#include <iostream>

int main()
{
    
  class __lambda_5_12
  {
    public: 
    inline /*constexpr */ int operator()(int a) const
    {
      std::cout.operator<<(a).operator<<(std::endl);
      return a;
    }
    
    using retType_5_12 = int (*)(int);
    inline /*constexpr */ operator retType_5_12 () const noexcept
    {
      return __invoke;
    };
    
    private: 
    static inline int __invoke(int a)
    {
      std::cout.operator<<(a).operator<<(std::endl);
      return a;
    }
    
    
  };
  
  __lambda_5_12 f = __lambda_5_12{};
}

可以看到,通过 operator type 的方式,可以将这个类给转换成一个 type ,这里的 type 就是这个函数指针。

带 captures 的 lambda

一旦加了capture,就不像刚才那样可以直接转为一个函数指针了:

#include <iostream>

int main()
{
  	int b = 0;
 	auto f = [&b](int a){std::cout << a << std::endl; return a;};
}

网站解析如下:

#include <iostream>

int main()
{
  int b = 0;
    
  class __lambda_6_12
  {
    public: 
    inline /*constexpr */ int operator()(int a) const
    {
      std::cout.operator<<(a).operator<<(std::endl);
      return a;
    }
    
    private: 
    int & b;
    
    public:
    __lambda_6_12(int & _b)
    : b{_b}
    {}
    
  };
  
  __lambda_6_12 f = __lambda_6_12{b};
}

可以看到,其变成了一个彻彻底底的仿函数。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值