相关疑难解决方法(0)

为什么有时不需要在lambda中捕获const变量?

请考虑以下示例:

#include <cstdlib>

int main() {
    const int m = 42;
    [] { m; }(); // OK

    const int n = std::rand();
    [] { n; }(); // error: 'n' is not captured
}
Run Code Online (Sandbox Code Playgroud)

为什么我需要捕获n第二个lambda而不是m第一个lambda?我在C++ 14标准中检查了第5.1.2节(Lambda表达式)但我无法找到原因.你能指点我解释一个段落吗?

更新:我在GCC 6.3.1和7(主干)中观察到了这种行为.Clang 4.0和5(主干)在两种情况下都失败并出错(variable 'm' cannot be implicitly captured in a lambda with no capture-default specified).

c++ lambda const language-lawyer

70
推荐指数
2
解决办法
4898
查看次数

为什么这个嵌套的lambda不被认为是constexpr?

我正在尝试使用嵌套的constexpr lambdas创建一个curried接口,但编译器不认为它是一个常量表达式.

namespace hana = boost::hana;
using namespace hana::literals;

struct C1 {};

template < typename T,
           std::size_t size >
struct Array {};

constexpr auto array_ = [] (auto size) {
      return [=] (auto type) {
        return hana::type_c<Array<typename decltype(type)::type, size()>>;
      };
    };

int main() {

  constexpr auto c1 = hana::type_c<C1>;
  constexpr auto test = hana::type_c<Array<typename decltype(c1)::type, hana::size_c<100>()>>;
  constexpr auto test2 = array_(hana::size_c<100>)(c1);
}
Run Code Online (Sandbox Code Playgroud)

我之前发布了一个问题,因为我找到了一个不同的最小例子,但这还不够.

错误:

test2.cpp: In instantiation of ‘<lambda(auto:1)>::<lambda(auto:2)> [with auto:2 = boost::hana::type_impl<C1>::_; auto:1 = boost::hana::integral_constant<long unsigned int, 100>]’:
test2.cpp:31:54: …
Run Code Online (Sandbox Code Playgroud)

c++ lambda metaprogramming boost-hana c++17

7
推荐指数
2
解决办法
982
查看次数