gpt4 book ai didi

c++ - 常量的编译时检查

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:48:09 27 4
gpt4 key购买 nike

如果我有一个函数

int calcStuff_dynamic(const int a, const int b)

和一些模板元代码

template<int a, int b>
struct calcStuff_static {
static const int value = //some more code
};

有没有办法写一个包装器

int calcStuff(const int a, const int b) {
IF_THESE_ARE_KNOWN_CONSTANTS_AT_COMPILE_TIME(a, b)
return calcStuff_static<a, b>::value;
ELSE_TEMPLATE_WOULD_FAIL
return calcStuff_dynamic(a, b);
}

最佳答案

你做不到,但它会被聪明的编译器完成。

也许想到的第一个解决方案是结合使用 SFINAEconstexpr 值。在这种情况下,我们需要一些东西来检测 constexpr 值。

但是,没有 is_constexpr 或类似的东西来检测编译时已知的值。另一方面,函数 is_const 没有用,因为 constexpr 不是类型的一部分。所以,你不能那样做(或者至少我不知道直接的解决方案)。

但是,如果您知道许多编译器都进行了优化,可以在编译时针对已知值计算函数的最终值,那么您会很高兴。例如在 GCC 中,有“SCEV final value replacement”

因此,您应该只在参数未知时使用该动态函数,编译器会按照您的意愿执行(如果可能的话)。

关于c++ - 常量的编译时检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24724225/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com