为什么C ++中的Lambda永远不会DefaultConstructible [英] Why is a lambda in C++ never DefaultConstructible

查看:52
本文介绍了为什么C ++中的Lambda永远不会DefaultConstructible的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的lambda不能捕获任何东西,例如

I'm having lambdas that don't capture anything, like

[](){};

我有一个模板类,其中包含这样的lambda.由于lambda不包含非静态数据成员,也不包含虚拟函数,因此应为空类,并且为DefaultConstructible.这只是可用于模板元编程的一种策略类.我想知道,为什么这样的类不能由C ++标准默认构造.

I have a template class, that contains such a lambda. Since the lambda does not contain non-static data members, nor virtual functions, it should be an empty class and DefaultConstructible. It's only a kind of policy class usable for template metaprogramming. I would like to know, why such a class is not default constructible by the C++ standard.

边注::了解如何Lambda闭包类型已删除默认构造函数,提出了一个不同的问题,尽管标题似乎非常相似.它询问如何在没有可用的默认构造函数的情况下创建无状态lambda对象.我在问为什么没有可用的默认构造函数.

Sidenote: Understanding how Lambda closure type has deleted default constructor is asking a different question, though the title seems to be very similar. It is asking how a stateless lambda-object is created without usable default constructor. I'm asking why there is no usable default constructor.

推荐答案

Lambda旨在被创建然后使用.该标准因此说不,他们没有默认构造函数".唯一的方法是通过lambda表达式或相同的副本.

Lambdas are intended to be created then used. The standard thus says "no, they don't have a default constructor". The only way to make one is via a lambda expression, or copies of same.

不是,因为它们的类型必须保留并使用.这样做可能会导致违反ODR的风险,并且要求编译器避免 ODR 违规将使符号处理过于复杂.

They are not intended for their types to be something you keep around and use. Doing so risks ODR violations, and requiring compilers to avoid ODR violations would make symbol mangling overly complex.

但是,在C ++ 17中,您可以围绕函数指针编写无状态包装器:

However, in C++17 you can write a stateless wrapper around a function pointer:

template<auto fptr>
struct function_pointer_t {
  template<class...Args>
  // or decltype(auto):
  std::result_of_t< std::decay_t<decltype(fptr)>(Args...) >
  operator()(Args&&...args)const
    return fptr(std::forward<Args>(args)...);
  }
};

并且 [](){} 上的操作符void(*)()

And as operator void(*)() on [](){} is constexpr in C++17, function_pointer_t<+[](){}> is a do-nothing function object that is DefaultConstructible.

这实际上并没有包装lambda,而是包装了lambda产生的指向函数的指针.

This doesn't actually wrap the lambda, but rather the pointer-to-function that the lambda produces.

这篇关于为什么C ++中的Lambda永远不会DefaultConstructible的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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