C++23中consteval构造函数调用constexpr模板成员函数的Clang编译问题
C++23 consteval构造函数调用模板constexpr成员函数的编译分歧
// gcc: ok // clang: compile error struct arg { consteval arg(const int i) // consteval : i_(i) { chk<int>(i); // error!! } template <typename T> constexpr void chk(const T i) // template member {} int i_; }; void f(arg i) {} int main() { f(10); return 0; }
在C++23环境下,GCC可正常编译上述代码,但Clang会拒绝编译,报错信息如下:
<source>:39:7: error: call to consteval function 'arg::arg' is not a constant expression 39 | f(10); | ^ <source>:23:9: note: undefined function 'chk<int>' cannot be used in a constant expression 23 | chk<int>(i); | ^
测试了几种修改方式,均可解决Clang的编译错误:
- 将
arg::arg构造函数改为constexpr,错误消失; - 将
arg::chk()改为非模板成员函数,编译通过; - 将
chk()改为普通非成员模板函数,编译通过。
如果Clang的编译行为符合C++标准,想明确两个问题:
- 为何仅当
arg::chk()是模板成员函数时才会触发该错误? - Clang提示“undefined function 'chk
'”的具体原因是什么?
内容的提问来源于stack exchange,提问作者celeta
相关产品推荐
相关产品推荐

