[英]How to do the conditional variable initialization at compiler time?
C ++ 11标准具有std::conditional<>
模板,用于在编译器时通过某种布尔条件进行类型选择。 如何进行相同的操作但是为变量初始化选择init值? 类似于type a = (exp) ? first_value : second_value;
type a = (exp) ? first_value : second_value;
。
我用我的模板:
template<bool B, typename T>
inline constexpr T&& conditional_initialize(T&& i1, T&& i2) {
return B ? std::move(i1) : std::move(i2);
}
但它只能用于POD类型: int a = conditional_initialize<true>(1, 2);
。 对于数组初始化,此模板编译时出错。 错误的编译示例: int a[] = conditional_initialize<true>({1, 2}, {3,4,5});
谁可以帮我模板?
template<class T, std::size_t N, std::size_t M, bool b>
std::array<T, b?N:M>
conditional_array( std::array<T, N>&& lhs, std::array<T, M>&& rhs ) {
return std::move(std::get<b?0:1>( std::tie(lhs, rhs) ) );
}
这给你:
auto a = conditional_array<int,2,3,true>({{1, 2}}, {{3,4,5}});
这很接近。
通常, {}
构造不是表达式,它们不能通过任何机制通过另一个变量完美地转发。
我们还可以得到:
auto a = cond_init<true>( make_array(1,2), make_array(3,4,5) );
多做一点工作。
template<bool Test, class A, class B>
std::conditional_t<Test,A,B>
cond_init(A a, B b) {
return std::move( std::get<Test?0:1>( std::tie(a,b) ) );
}
template<class T0, class...Ts>
std::array< std::decay_t<T0>, sizeof...(Ts)+1 >
make_array( T0&& t0, Ts&&...ts ) {
return {{std::forward<T0>(t0), std::forward<Ts>(ts)...}};
}
我没有做这些constexpr
,因为懒惰。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.