简体   繁体   中英

How can I call a set of variadic base class constructors based on tagged argument packs?

I'd like to be able to do this:

template<typename Mix>
struct A {
  A(int i) { }
};

template<typename Mix>
struct B {
  B() { }
  B(const char*) { }
};

template<template<typename> class... Mixins>
struct Mix : Mixins<Mix<Mixins...>>... {
   // This works, but forces constructors to take tuples
   template<typename... Packs>
   Mix(Packs... packs) : Packs::Type(packs.constructorArgs)... { }
};

template<template<typename> class MixinType, typename... Args>
struct ArgPack {
  typedef MixinType Type; // pretend this is actually a template alias
  tuple<Args...> constructorArgs;
  ArgPack(Args... args) : constructorArgs(args...) { }
}

template<typename... Args>
ArgPack<A, Args...> A_(Args... args) {
  return ArgPack<A, Args...>(args...);
}

template<typename... Args>
ArgPack<B, Args...> B_(Args... args) {
  return ArgPack<B, Args...>(args...);
}

Mix<A, B> m(); // error, A has no default constructor

Mix<A, B> n(A_(1)); // A(int), B()
Mix<A, B> n(A_(1), B_("hello"); // A(int), B(const char*)

How do I fill in /* mysterious code here */ to do what I want, to provide a nice interface for calling some set of constructors of mixins? I have a solution that works by making all non-null constructs actually take a tuple of args, and then overloading figures out which one to call, but I would like to avoid constraining mixin authors by making them write a constructor A(tuple), instead of just A(int, int).

Thanks!

I think I understand what you want. std::pair has a similar feature:

std::pair<T, U> p(std::piecewise_construct
                      , std::forward_as_tuple(foo, bar)
                      , std::forward_as_tuple(qux) );
// p.first constructed in-place as if first(foo, bar) were used
// p.second constructed in place as if second(qux) were used

As you can see this has a lot of benefits: exactly one T and U construction each takes place, neither T and U are required to be eg MoveConstructible, and this only costs the constructions of two shallow tuples. This also does perfect forwarding. As a warning though, this is considerably harder to implement without inheriting constructors, and I will use that feature to demonstrate a possible implementation of a piecewise-constructor and then attempt to make a variadic version of it.

But first, a neat utility that always come in handy when variadic packs and tuples are involved:

template<int... Indices>
struct indices {
    using next = indices<Indices..., sizeof...(Indices)>;
};

template<int Size>
struct build_indices {
    using type = typename build_indices<Size - 1>::type::next;
};
template<>
struct build_indices<0> {
    using type = indices<>;
}

template<typename Tuple>
constexpr
typename build_indices<
    // Normally I'd use RemoveReference+RemoveCv, not Decay
    std::tuple_size<typename std::decay<Tuple>::type>::value
>::type
make_indices()
{ return {}; }

So now if we have using tuple_type = std::tuple<int, long, double, double>; then make_indices<tuple_type>() yields a value of type indices<0, 1, 2, 3> .

First, a non-variadic case of piecewise-construction:

template<typename T, typename U>
class pair {
public:
    // Front-end
    template<typename Ttuple, typename Utuple>
    pair(std::piecewise_construct_t, Ttuple&& ttuple, Utuple&& utuple)
        // Doesn't do any real work, but prepares the necessary information
        : pair(std::piecewise_construct
                   , std::forward<Ttuple>(ttuple), std::forward<Utuple>(utuple)
                   , make_indices<Ttuple>(), make_indices<Utuple>() )
     {}

private:
    T first;
    U second;

    // Back-end
    template<typename Ttuple, typename Utuple, int... Tindices, int... Uindices>
    pair(std::piecewise_construct_t
             , Ttuple&& ttuple, Utuple&& utuple
             , indices<Tindices...>, indices<Uindices...>)
        : first(std::get<Tindices>(std::forward<Ttuple>(ttuple))...)
        , second(std::get<Uindices>(std::forward<Utuple>(utuple))...)
    {}
};

Let's try plugging that with your mixin:

template<template<typename> class... Mixins>
struct Mix: Mixins<Mix<Mixins...>>... {
public:
    // Front-end
    template<typename... Tuples>
    Mix(std::piecewise_construct_t, Tuples&&... tuples)
        : Mix(typename build_indices<sizeof...(Tuples)>::type {}
                  , std::piecewise_construct
                  , std::forward_as_tuple(std::forward<Tuples>(tuples)...)
                  , std::make_tuple(make_indices<Tuples>()...) )
    {
        // Note: GCC rejects sizeof...(Mixins) but that can be 'fixed'
        // into e.g. sizeof...(Mixins<int>) even though I have a feeling
        // GCC is wrong here
        static_assert( sizeof...(Tuples) == sizeof...(Mixins)
                       , "Put helpful diagnostic here" );
    }

private:
    // Back-end
    template<
        typename TupleOfTuples
        , typename TupleOfIndices
        // Indices for the tuples and their respective indices
        , int... Indices
    >
    Mix(indices<Indices...>, std::piecewise_construct_t
            , TupleOfTuples&& tuple, TupleOfIndices const& indices)
        : Mixins<Mix<Mixins...>>(construct<Mixins<Mix<Mixins...>>>(
            std::get<Indices>(std::forward<TupleOfTuples>(tuple))
            , std::get<Indices>(indices) ))...
    {}

    template<typename T, typename Tuple, int... Indices>
    static
    T
    construct(Tuple&& tuple, indices<Indices...>)
    {
        using std::get;
        return T(get<Indices>(std::forward<Tuple>(tuple))...);
    }
};

As you can see I've gone one level higher up with those tuple of tuples and tuple of indices. The reason for that is that I can't express and match a type such as std::tuple<indices<Indices...>...> (what's the relevant pack declared as? int...... Indices ?) and even if I did pack expansion isn't designed to deal with multi-level pack expansion too much. You may have guessed it by now but packing it all in a tuple bundled with its indices is my modus operandi when it comes to solving this kind of things... This does have the drawback however that construction is not in place anymore and the Mixins<...> are now required to be MoveConstructible.

I'd recommend adding a default constructor, too (ie Mix() = default; ) because using Mix<A, B> m(std::piecewise_construct, std::forward_as_tuple(), std::forward_as_tuple()); looks silly. Note that such a defaulted declaration would yield no default constructor if any of the Mixin<...> is not DefaultConstructible.

The code has been tested with a snapshot of GCC 4.7 and works verbatim except for that sizeof...(Mixins) mishap.

I faced a very similar problem in the context of a Policy based design. Basically i have my class inherit behaviour from a set of Policies, and some of them are stateful and need constructor initialization.

The solution i found is to have the policy classes organized in a deep hierarchy, instead of a wide one. This allows to write constructors which take just the elements they need from an argument pack and pass along the remaining pack to initialize the "top" part of the hierarchy.

Here is my code:

/////////////////////////////////////////////
//               Generic part              //
/////////////////////////////////////////////
template<class Concrete,class Mother,class Policy>
struct PolicyHolder{};

struct DeepHierarchyFinal{};

template<class Concrete,class P,typename... Args>
struct DeepHierarchy:   public PolicyHolder<Concrete,DeepHierarchy<Concrete,Args...>,P>,
                        public P
{
    template<typename... ConstructorArgs>
    DeepHierarchy(ConstructorArgs... cargs):
    PolicyHolder<Concrete,DeepHierarchy<Concrete,Args...>,P>(cargs...){};
};

template<class Concrete,class P>
struct DeepHierarchy<Concrete,P>:   public PolicyHolder<Concrete,DeepHierarchyFinal,P>,
                                    public P
{
    template<typename... ConstructorArgs>
    DeepHierarchy(ConstructorArgs... cargs):
    PolicyHolder<Concrete,DeepHierarchyFinal,P>(cargs...){};
};
///////////////////////////////////////////
//                Test case              //
///////////////////////////////////////////

///////////////////////////////////////////
//                Policies               //
///////////////////////////////////////////
struct Policy1{};
struct Policy2{};
struct Policy3{};
struct Policy4{};

template<class Concrete,class Mother>
struct PolicyHolder<Concrete,Mother,Policy1> : public Mother
{
    int x;
    template<typename... Args>
    PolicyHolder(int _x,Args... args):Mother(args...),x(_x) {};
};

template<class Concrete,class Mother>
struct PolicyHolder<Concrete,Mother,Policy2> : public Mother
{
    template<typename... Args>
    PolicyHolder(Args... args):Mother(args...){
        cout<<"Policy2 initialized";
        // Here is a way to know (at runtime) if a particular
        // policy has been selected in the concrete class
        if (boost::is_convertible<Concrete,Policy3>::value)
            cout<<" together with Policy3\n";
        else
            cout<<" without Policy3\n";
    };
};

template<class Concrete,class Mother>
struct PolicyHolder<Concrete,Mother,Policy3> : public Mother
{
    string s;
    char c;
    template<typename... Args>
    PolicyHolder(string _s,char _c,Args... args):Mother(args...), s(_s),c(_c) {};
};

template<class Concrete,class Mother>
struct PolicyHolder<Concrete,Mother,Policy4> : public Mother
{
    template<typename... Args>
    PolicyHolder(Args... args):Mother(args...) {
        // Here is a way to check (at compile time) that 2 incompatible policies
        // does not coexist
        BOOST_STATIC_ASSERT(( ! boost::is_convertible<Concrete,Policy1>::value));
    };
};
//////////////////////////////////////////////
//              Concrete class              //
//////////////////////////////////////////////
template<class... PoliciesPack>
struct C: public DeepHierarchy<C<PoliciesPack...>,PoliciesPack...>
{
    using Policies=DeepHierarchy<C<PoliciesPack...>,PoliciesPack...>;
    string s;
    template<typename... Args>
    C(string _s,Args... args):Policies(args...),s(_s){};
};

BOOST_AUTO_TEST_CASE( testDeepHierarchyConstruction )
{
    C<Policy1,Policy2> c0("foo",4);
    BOOST_CHECK_EQUAL(c0.x,4);

    C<Policy1,Policy2,Policy3> c1("bar",3,"foo",'f');
    BOOST_CHECK_EQUAL(c1.c,'f');

    C<Policy3,Policy4> c2("rab","oof",'d');
    BOOST_CHECK_EQUAL(c2.c,'d');
}

I made a more extensive analisys of this approach at this page .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM