考虑以下代码:
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。
答案 0 :(得分:4)
正如@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...
};
答案 1 :(得分:1)
您可以将所有常量打包到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...
};
但不确定它是否更好。