c – 如何从模板参数包中删除类型?

前端之家收集整理的这篇文章主要介绍了c – 如何从模板参数包中删除类型?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在寻找一种从模板参数包中删除(让我们说现在所有的发生)一种类型的方法.最终结果将是一个看起来像这样的结构:
  1. template<typename T,typename...Ts>
  2. struct RemoveT
  3. {
  4. using type = /* a new type out of Ts that does not contain T */
  5. }

让我们说边缘案例RemoveT< int,int>将通过返回void来处理(未在下面的代码中处理).我的初始设计如下所示:

  1. // --------------------------------------------------------------
  2. // 1. A "way" of typedefing variadic number of types ------------
  3. template<typename...Ts>
  4. struct pack {
  5. using type = Ts;
  6. };
  7. // --------------------------------------------------------------
  8.  
  9. // --------------------------------------------------------------
  10. template<typename T,typename...Ts> struct RemoveT;
  11.  
  12. template<typename T,typename T1,typename...Ts>
  13. struct RemoveT {
  14. using type = typename pack<T1,typename RemoveT<T,Ts...>::type>::type;
  15. };
  16.  
  17. template<typename T,typename T1>
  18. struct RemoveT<T,T1> {
  19. using type = T1;
  20. };
  21.  
  22. template<typename T,typename...Ts>
  23. struct RemoveT<T,T,Ts...> {
  24. using type = typename RemoveT<Ts...>::type;
  25. };
  26. // --------------------------------------------------------------

现在我甚至不能开始测试这个代码,因为the pack structure is not valid C++

重述

为了防止这样做有助于解决问题

人们可以认为,这个包根本就没有用处.我们可以绕过RemoveT结构,创建一个只包含所需类型的新的RemoveT.然后,在从结构体中提取类型时,该问题将转换
>我们可以创建类型对,模仿类型列表的行为,并采取更递归的方法.

底线

对于各种类型的Ts和一个类型T:我可以创建我们的Ts ommit T吗?

解决方法

以下提供了一种非递归和直接的方法来从Ts …删除T,并且像Jarod42的解决方案一样,产生一个std :: tuple< Us ...>但不需要使用typename … :: type:
  1. #include <tuple>
  2. #include <type_traits>
  3.  
  4. template<typename...Ts>
  5. using tuple_cat_t = decltype(std::tuple_cat(std::declval<Ts>()...));
  6.  
  7. template<typename T,typename...Ts>
  8. using remove_t = tuple_cat_t<
  9. typename std::conditional<
  10. std::is_same<T,Ts>::value,std::tuple<>,std::tuple<Ts>
  11. >::type...
  12. >;
  13.  
  14.  
  15. int main()
  16. {
  17. static_assert(std::is_same<
  18. remove_t<int,int,char,float,int>,std::tuple<char,float>
  19. >::value,"Oops");
  20. }

Live example

猜你在找的C&C++相关文章