問題描述
我知道這就像打開潘多拉盒子,但它并沒有停止打擾我.考慮一個簡單的例子:
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);
}
我知道 lambdas 不能在未評估的上下文中聲明,但顯然這里不是這種情況.還有什么更奇怪的 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 表達式是一個純右值,其結果對象稱為閉包對象.lambda 表達式不得出現在未求值的操作數、模板參數、別名聲明、typedef 聲明或函數聲明中或函數體外的函數模板聲明中和默認參數.
A lambda-expression is a prvalue whose result object is called the closure object. A lambda-expression shall not appear in an unevaluated operand, in a template-argument, in an alias-declaration, in a typedef declaration, or in the declaration of a function or function template outside its function body and default arguments.
從我標記為粗體的部分可以看出,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:
[ 注意:目的是防止 lambda 出現在簽名中.— 尾注 ]
[?Note: The intention is to prevent lambdas from appearing in a signature. —?end note?]
如果我猜的話,我會說這個錯誤是因為從 C++17 開始,lambdas 是隱式的 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 嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!