具有相同 bool 值的多个编译时检查。如何只检查一次?

Multiple compile-time checks with the same bool value. How to check just once?

考虑这段代码:

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...
    };

您可以将所有常量打包到 tuple

template <int A, int B, typename T>
struct Object {
private:
    static constexpr std::tuple<bool, int, char, double> t = (A < B) ?
        { true, A, 'a', 1.5 } :
        { false, B, 'b', 3.14};
public:
    static constexpr bool check = std::get<0>(t);
    static constexpr int value = std::get<1>(t);
    static constexpr char c = std::get<2>(t);
    static constexpr double d = std::get<3>(t);;
    using type = typename std::conditional<check, T, int>::type;
    // etc...
};

但不确定是否更好。