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

能否在编译时调用static constexpr成员函数?g++与clang++分歧求解

g与clang对编译期调用static constexpr成员函数的行为分歧

g和clang在判断能否在编译期调用static constexpr成员函数时存在行为差异,以下示例代码可复现该问题:

#include <print>

struct foo {
  static constexpr int max_size() { return 0; }
};

struct bar {
};

void report(const char *name, const auto &&x)
{
  if constexpr (requires { requires x.max_size() < 5; })
    std::println("{} is okay", name);
  else
    std::println("{} is not okay", name);
}

int main()
{
  report("foo", foo{});
  report("bar", bar{});
}

两款编译器的编译结果

Clang 18.1.8

编译命令:

clang++ -std=c++23 -O2 -Wall -Werror constexpr.cc -o constexpr

输出:

foo is not okay
bar is not okay

g++ 14.1.1

编译命令:

g++ -std=c++23 -O2 -Wall -Werror constexpr.cc -o constexpr

输出:

foo is okay
bar is not okay

符合C++标准的行为

根据C标准,类的static成员函数允许通过对象实例调用,因此x.max_size()的写法合法,g的行为符合标准,clang此处表现属于编译器实现问题。

临时解决方案

若将requires表达式中的判断条件改为decltype(auto(x))::max_size() < 5,两款编译器的输出都会与上述g++的结果一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 22:39:54