简体   繁体   English

如果在编译时声明const值

[英]If statements on compile-time const value

I want to have code included in a function based on a compile time constant value, but static_if is not a construct in C++. 我想让代码包含在基于编译时常量值的函数中,但是static_if不是C ++中的构造。

So I can write functions like this 所以我可以这样写函数

class TA {
public:
    template<bool flag>
    void func() {
        if(flag)
            a++;
    }

    int a;
};


int main() {
    TA a;
    a.func<true>();
    a.func<false>();
}

And I want to have a guarantee that the compiler makes two functions. 而且我想保证编译器具有两个功能。 One where 'if(flag) a++' is compiled into the function and one where it is not. 一种是将“ if(flag)a ++”编译到函数中,另一种则不是。

Is it possible to get this guarantee based on the C++17 standard, or am I at the mercy of the compiler vendor? 是否有可能基于C ++ 17标准获得此保证,还是由编译器供应商摆布?

Thanks. 谢谢。

In actual fact, C++17 does include exactly what you're asking about - it's callled if constexpr . 实际上,C ++ 17确实包含了您所要询问的内容,即if constexpr

You can use it anywhere your condition can be evaluated at compile time (such as template instantiation): 您可以在编译时可以评估条件的任何地方使用它(例如模板实例化):

class TA {
public:
    template<bool flag>
    void func() {
        if constexpr (flag)
            a++;
    }

    int a;
};

However, as others have said, in this example you're unlikely to gain much as the compiler can often optimize stuff like this. 但是,正如其他人所说,在此示例中,您不太可能获得太多收益,因为编译器通常可以优化此类内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM