You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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++标准,想明确两个问题:

  1. 为何仅当arg::chk()是模板成员函数时才会触发该错误?
  2. Clang提示“undefined function 'chk'”的具体原因是什么?

内容的提问来源于stack exchange,提问作者celeta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 13:55:09