[英]How do I switch/select types during compile-time?
Is there a standard way for me to select a type at compile-time on an unsigned index in c++11? 我是否有一种标准方法可以在编译时在c ++ 11中的无符号索引上选择类型?
For example, something like: 例如,类似于:
using type_0 = static_switch<0,T,U>; // yields type T
using type_1 = static_switch<1,T,U>; // yields type U
If there is a variadic-template version, it would be very useful. 如果有一个variadic-template版本,那将非常有用。
This should work: 这应该工作:
template<std::size_t N, typename... T>
using static_switch = typename std::tuple_element<N, std::tuple<T...> >::type;
Another method: 另一种方法:
template<std::size_t N, typename T, typename... Ts>
struct static_switch {
using type = typename static_switch<N - 1, Ts...>::type;
};
template<typename T, typename... Ts>
struct static_switch<0, T, Ts...> {
using type = T;
};
You could probably use a boost::mpl::vector
to store your types and use boost::mpl::at<v,n>::type
to get a type with from the index. 您可以使用
boost::mpl::vector
来存储您的类型,并使用boost::mpl::at<v,n>::type
来获取索引中的类型。
template<std::size_t N, typename... T>
using static_switch = typename boost::mpl::at<boost::mpl::vector<T...>, N>::type;
How about 怎么样
template<size_t N, typename T, typename U>
struct static_switch {};
template<typename T, typename U>
struct static_switch<0, T, U>{typedef T type;};
template<typename T, typename U>
struct static_switch<1, T, U>{typedef U type;};
You would use it as follows: 您可以按如下方式使用它:
using type_0 = static_switch<0,T,U>::type; // yields type T
using type_1 = static_switch<1,T,U>::type; // yields type U
This is more or less implemented for you in std::conditional . 在std :: conditional中或多或少地为您实现了这一点。
With C++17 you can also go about this another way. 使用C ++ 17,您也可以采用另一种方式。 Instead of calculating the type explicitly you can use
constexpr if
and do different things (including returning different types) directly: 而不是明确地计算类型,您可以使用
constexpr if
并执行不同的操作(包括直接返回不同的类型):
template<size_t N>
decltype(auto) foo(){
if constexpr(N%2==0){
return std::string("Hello I'm even");
}else{
return std::pair(
std::vector<char>{'O','d','d',' ','v','a','l','u','e'},
[](){ return N; });
}
}
foo<0>() // "Hello I'm even"
foo<21>().second() // 21
You can also use this to get just the type: 您也可以使用它来获取类型:
using type_0 = decltype(foo<0>());
using type_1 = decltype(foo<1>());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.