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

使用constexpr兼顾编译时与运行时求值——传递常量参数问题

问题:constexpr函数传递编译期常量参数时的求值时机控制

需求背景

我需要实现一个支持编译期、运行时双场景执行的constexpr函数,它接收unsigned long类型参数并返回对应数值。由于参数可能是编译期已知常量,也可能是运行时变量,所以不能使用consteval(它要求必须在编译期求值)。

现有代码

#include <iostream>
#include <cstdint>
#include <cstdlib>

constexpr std::uint32_t GetFlagFromFlagName(unsigned long FlagName)
{
    if (!std::is_constant_evaluated())
    {
        std::cout << "Running function at runtime" << '\n';
    }

    switch (FlagName)
    {
    case 0:
        return 10;
    case 1:
        return 20;
    default:
        return 0;
    }
}

void MyTestFunc(std::uint32_t test)
{
    std::cout << "test>>>" << test << "\n";
}

int main()
{
    constexpr auto CompileTimeVariable = GetFlagFromFlagName(0); // 预期编译期执行
    std::cout << "CompileTimeVariable result>>>" << CompileTimeVariable << "\n";

    MyTestFunc(GetFlagFromFlagName(0)); // 实际运行时执行,不符合预期

    system("pause");
}

注:补全了必要头文件以确保代码可正常编译运行。

当前运行结果

CompileTimeVariable result>>>10 
Running function at runtime 
test>>>10

预期输出

CompileTimeVariable result>>>10 
test>>>10

核心疑问

第二次调用GetFlagFromFlagName(0)时,传入的是明确的编译期常量0,但函数却在运行时执行,导致打印了不必要的运行时提示。我知道将函数结果赋值给constexpr变量可以强制编译期求值,但想请教:有没有办法不用单独声明变量,直接传递函数结果就能触发编译期求值?尝试过(constexpr)GetFlagFromFlagName(0)这种强制转换写法,但编译器不支持。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 11:36:01