Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" 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?

like image 327
Ludovicio Avatar asked Jul 24 '17 19:07

Ludovicio


1 Answers

You probably want this:

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;`.
like image 144
HolyBlackCat Avatar answered Sep 30 '22 03:09

HolyBlackCat