本文介绍了我可以在模板参数中声明constexpr lambda吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这就像打开Pandora盒子一样,但是它并没有停止打扰我.考虑一个简单的例子:

I know it's like opening the Pandora box but it doesn't stop bothering me. Consider a simple example:

#include <type_traits>

template <auto>
struct Foo: std::false_type { };

template <>
struct Foo<[](){return 1;}()>:std::true_type { };

int main() {
    static_assert(Foo<1>::value);
}

我知道不能在未评估的上下文中声明lambda,但显然不是这种情况.更奇怪的clang 5.0.0(我想它首先部分支持constexpr lambda)可以对其进行编译.

I know lambdas cannot be declared inside unevaluated context, but obviously this is not the case here. What is even more weird clang 5.0.0 (which, I guess, first partially supports constexpr lambda) does compile it.

是编译器错误还是C ++ 17允许这样做?

Is it a compiler bug or will C++17 allow this?

推荐答案

否,那是编译器错误. gcc 7.1 正确地拒绝了该代码.

No, that is a compiler bug. gcc 7.1 correctly rejects the code.

[expr.prim.lambda]/2 :

从我标记为粗体的部分可以看到,lambda表达式不能出现在模板参数列表中.

As you can see from the part that I marked as bold, a lambda expression cannot appear in a template argument list.

在随后的注释中也对此进行了明确说明:

This is also made clear in a subsequent note:

如果我猜到了,我会说这个错误的产生是因为从C ++ 17开始,lambda隐式地是constexpr,这使得它们在编译时表达式(如模板参数)中被调用是有效的.但是实际上在模板参数中定义lambda仍然是非法的.

If I were to guess, I would say that the bug comes about because starting with C++17, lambdas are implicitly constexpr, which makes them valid to be called in compile time expressions, like template arguments. But actually defining a lambda in a template argument is still illegal.

请注意,此限制已在C ++ 20中取消. :)

Note that this restriction has been lifted in C++20. :)

这篇关于我可以在模板参数中声明constexpr lambda吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 23:55
查看更多