微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正在寻找一种从模板参数包中删除(让我们说现在所有的发生)一种类型的方法.最终结果将是一个看起来像这样的结构:
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 pack structure is not valid C++

重述

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

人们可以认为,这个包根本就没有用处.我们可以绕过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

原文地址:https://www.jb51.cc/c/113884.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐