c – 如何从模板参数包中删除类型?
发布时间:2020-12-16 05:43:35 所属栏目:百科 来源:网络整理
导读:我正在寻找一种从模板参数包中删除(让我们说现在所有的发生)一种类型的方法.最终结果将是一个看起来像这样的结构: templatetypename T,typename...Tsstruct RemoveT{ using type = /* a new type out of Ts that does not contain T */} 让我们说边缘案例Re
我正在寻找一种从模板参数包中删除(让我们说现在所有的发生)一种类型的方法.最终结果将是一个看起来像这样的结构:
template<typename T,typename...Ts> struct RemoveT { using type = /* a new type out of Ts that does not contain T */ } 让我们说边缘案例RemoveT< int,int>将通过返回void来处理(未在下面的代码中处理).我的初始设计如下所示: // -------------------------------------------------------------- // 1. A "way" of typedefing variadic number of types ------------ template<typename...Ts> struct pack { using type = Ts; }; // -------------------------------------------------------------- // -------------------------------------------------------------- template<typename T,typename...Ts> struct RemoveT; template<typename T,typename T1,typename...Ts> struct RemoveT { using type = typename pack<T1,typename RemoveT<T,Ts...>::type>::type; }; template<typename T,typename T1> struct RemoveT<T,T1> { using type = T1; }; template<typename T,typename...Ts> struct RemoveT<T,T,Ts...> { using type = typename RemoveT<Ts...>::type; }; // -------------------------------------------------------------- 现在我甚至不能开始测试这个代码,因为the 重述 为了防止这样做有助于解决问题 人们可以认为,这个包根本就没有用处.我们可以绕过RemoveT结构,创建一个只包含所需类型的新的RemoveT.然后,在从结构体中提取类型时,该问题将转换 底线 对于各种类型的Ts和一个类型T:我可以创建我们的Ts ommit T吗? 解决方法
以下提供了一种非递归和直接的方法来从Ts …删除T,并且像Jarod42的解决方案一样,产生一个std :: tuple< Us ...>但不需要使用typename … :: type:
#include <tuple> #include <type_traits> template<typename...Ts> using tuple_cat_t = decltype(std::tuple_cat(std::declval<Ts>()...)); template<typename T,typename...Ts> using remove_t = tuple_cat_t< typename std::conditional< std::is_same<T,Ts>::value,std::tuple<>,std::tuple<Ts> >::type... >; int main() { static_assert(std::is_same< remove_t<int,int,char,float,int>,std::tuple<char,float> >::value,"Oops"); } Live example (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |