考虑以下伪代码:
template<class... T>
struct worker : unique<T...>::type...{};
struct x{};
struct y{};
struct z{};
是否可以编写模板unique
,使其生成仅包含T
个中唯一类型的参数包,以便worker<x,y,x,z>
直接从{{1}派生}},x
,y
按顺序,给定z
s是非最终类?
答案 0 :(得分:7)
AFAIK:没有。
问题是type
是typedef
指令的结果,typedef
不能对包进行别名。这实际上是一个麻烦,并且通常在包上的计算需要引入包装类型(例如template <typename...> struct pack {};
)才能传递它们。
答案 1 :(得分:4)
Parameter packs cannot be easily stored,所以我不认为你想做什么。但是,由于您似乎需要此功能才能从一组基础继承,您可以使用一些模板元编程来创建从您的集合中的所有基础线性继承的基本类型。在此之前,您可以轻松地从参数包中过滤重复项。
以下是使用Boost.MPL:
的此方法的实现#include <boost/mpl/fold.hpp>
#include <boost/mpl/inherit.hpp>
#include <boost/mpl/inherit_linearly.hpp>
#include <boost/mpl/insert.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/mpl/set.hpp>
#include <boost/mpl/vector.hpp>
namespace mpl = boost::mpl;
template < typename ...Args >
struct inherit_uniquely
{
// filter out duplicates
typedef typename
mpl::fold<
mpl::vector< Args... >,
mpl::set0<>,
mpl::insert< mpl::_1, mpl::_2 >
>::type unique_bases;
// create base type
typedef typename
mpl::inherit_linearly<
unique_bases,
mpl::inherit< mpl::_1, mpl::_2 >
>::type type;
};
template < typename ...Bases >
struct Derived : inherit_uniquely< Bases... >::type
{};
struct X { int x;};
struct Y { int y;};
struct Z { int z;};
int main()
{
Derived< X, Y, Z > d;
d.x = 1;
d.y = 2;
d.z = 3;
X& d_as_x = d;
Y& d_as_y = d;
Z& d_as_z = d;
}