考虑以下代码:

template <int A, int B, typename T>
struct Object {
    static constexpr bool check = A < B;
    static constexpr int value = check ? A : A+1;
    static constexpr char c = check ? 'a' : 'b';
    static constexpr double d = check ? 1.5 : 3.14;
    using type = typename std::conditional<check, T, int>::type;
    // etc...
};

如何重写上面的内容,以便仅检查一次check?毕竟,它始终是相同的值。一切都必须是constexpr。

最佳答案

正如@Nawaz所说,优化是没有意义的。运行时不会有任何好处,并且编译器足够聪明,可以在编译时优化条件,因此在编译时不应有太多开销。

在任何情况下,只要您同意采用模板特化路线,就可以实现您的设想。您可以将条件分为两个单独的专长,并利用它们来确定适合您的问题的constexpr

template <int A, int B, typename T, bool check = A / B >
    struct Object {
        static constexpr  int value = A;
        static constexpr  char c = 'a';
        static constexpr  double d = 1.5;
        using type = T;
        // etc...
    };
    template <int A, int B, typename T>
    struct Object<A,B,T,false> {
        static constexpr  int value =  A + 1;
        static constexpr  char c = 'b';
        static constexpr  double d =  3.14;
        using type = int;
        // etc...
    };

关于c++ - 具有相同bool值的多个编译时检查。如何只检查一次?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29895374/

10-11 22:42
查看更多