编译constness的时间检查

use*_*118 5 c++ templates compile-time-constant compile-time template-meta-programming

如果我有一个功能

int calcStuff_dynamic(const int a, const int b)
Run Code Online (Sandbox Code Playgroud)

和一些模板元代码

template<int a, int b>
struct calcStuff_static {
    static const int value = //some more code
};
Run Code Online (Sandbox Code Playgroud)

有没有办法写一个包装器

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);
}
Run Code Online (Sandbox Code Playgroud)

mas*_*oud 1

你做不到,但它会由智能编译器来完成。

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

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

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

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