Clang 19.1.0拒绝嵌套模板Lambda的问题咨询
Clang 19.1.0编译模板Lambda代码报错问题
下面这段代码在Clang 19.1.0中编译报错,但可以在旧版Clang、GCC及MSVC中正常编译:
template <typename> void func() { (void)[]<typename>() consteval { return []() { return 0; }.operator()(); }.template operator()<void>(); } template void func<void>();
Clang 19.1.0给出的报错信息如下:
<source>:4:16: error: cannot initialize object parameter of type 'const (lambda at <source>:4:16)' with an expression of type '(lambda at <source>:4:16)' 4 | return []() { | ^~~~~~ 5 | return 0; | ~~~~~~~~~ 6 | }.operator()(); | ~ <source>:7:16: note: in instantiation of function template specialization 'func()::(anonymous class)::operator()<void>' requested here 7 | }.template operator()<void>(); | ^ <source>:10:15: note: in instantiation of function template specialization 'func<void>' requested here 10 | template void func<void>(); | ^ 1 error generated. Compiler returned: 1
进行一些看似无关的微小修改即可让代码编译通过,这些修改包括:
- 将
func改为非模板函数 - 移除外层Lambda的模板(并将
.template operator()改为.operator()) - 将内层Lambda的
.operator()()改为() - 移除
consteval修饰符 - 将内层Lambda的调用结果存入变量后返回该变量
- 将内层Lambda存入变量后调用其
.operator()并返回结果
尽管这段代码较为晦涩,不太可能出现在生产环境中,但我并未发现代码存在语法错误。鉴于其他编译器(甚至旧版Clang)均允许编译,我认为这可能是编译器Bug。请问此行为是否有合理解释,还是如我猜测的是Bug?
内容的提问来源于stack exchange,提问作者Joel
相关产品推荐
相关产品推荐

