在编译期间如何切换/选择类型?(How do I switch/select types during compile

编程入门 行业动态 更新时间:2024-10-28 11:25:14
在编译期间如何切换/选择类型?(How do I switch/select types during compile-time?)

有没有一种标准的方式让我在编译时在c ++ 11的无符号索引中选择一个类型?

例如,像这样的东西:

using type_0 = static_switch<0,T,U>; // yields type T using type_1 = static_switch<1,T,U>; // yields type U

如果有一个可变模板版本,这将是非常有用的。

Is there a standard way for me to select a type at compile-time on an unsigned index in 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.

最满意答案

这应该工作:

template<std::size_t N, typename... T> using static_switch = typename std::tuple_element<N, std::tuple<T...> >::type;

另一种方法:

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

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

更多推荐

本文发布于:2023-07-31 15:12:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1345272.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   switch   select   types   compile

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!