C++ 11 模板,参数包的别名 [英] C++ 11 Templates, Alias for a parameter pack
问题描述
在个人项目中,我有这样的事情:
In a personal project i have something like this:
template <typename T>
class Base {
//This class is abstract.
} ;
template <typename T>
class DerivedA : public Base<T> {
//...
} ;
template <typename T>
class DerivedB : Base<T> {
//...
} ;
class Entity : public DerivedA<int>, DerivedA<char>, DerivedB<float> {
//this one inherits indirectly from Base<int>, Base<char> & Base<float>
};
Base"类是一种适配器,让我可以将实体"视为 int、char、float 或任何我想要的.派生A &DerivedB 有不同的方式来进行这种转换.然后我有一个类可以让我像这样存储实体的不同视图:
"Base" class is a kind of adaptor that let me see "Entity" as an int, a char, a float or whatever i want. DerivedA & DerivedB have different ways of do that conversion. Then i have a class that let me store different views of my entity like this:
template <typename... Args>
class BaseManager {
public:
void store(Args*... args){
//... do things
}
};
我有很多不同的实体"类,它们具有不同的基础"集合.我希望能够在别名中存储类型列表,例如:
I have a lot of different "Entity" classes which have different "Base" collections. I want to be able to store list of types in an alias like:
class EntityExtra : public DerivedA<int>, DerivedA<char>, DerivedB<float>{
public:
using desiredBases = Base<int>, Base<char>, Base<float>; /* here is the problem */
};
所以我可以这样使用它:
So i can use it this way:
EntityExtra ee;
BaseManager<Base<int>, Base<char>, Base<float> > bm; // <- I can use it this way
BaseManager<EntityExtra::desiredBases> bm; // <- I want to use it this way
bm.store(&ee,&ee,&ee); // The first ee will be converted to a Base<int>, the second to Base<char> and so on
有没有办法为任意类型列表创建别名,然后在模板参数包中使用它?
Is there a way to make an alias for an arbitrary list of types and then use it in a template parameter pack?
推荐答案
你可能想要这个:
template <typename ...P> struct parameter_pack
{
template <template <typename...> typename T> using apply = T<P...>;
};
// Example usage:
struct A {};
struct B {};
struct C {};
template <typename...> struct S {};
using my_pack = parameter_pack<A, B, C>;
my_pack::apply<S> var; // Equivalent to `S<A, B, C> var;`.
<小时>
在你的情况下,它可以这样使用:
In your case it could be used like this:
class EntityExtra : public DerivedA<int>, DerivedA<char>, DerivedB<float>{
public:
using desiredBases = parameter_pack<Base<int>, Base<char>, Base<float>>;
};
// ...
EntityExtra::desiredBases::apply<BaseManager> bm;
// Creates `BaseManager<Base<int>, Base<char>, Base<float>> bm;`.
这篇关于C++ 11 模板,参数包的别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!