How to Expand Call to Variadic Template Base Classes

How can I expand call to variadic template base classes?

Sure. You need a context that permits pack expansion - a simple one is a braced initializer list, which also has the benefit of guaranteeing left-to-right evaluation:

using expander = int[];
(void) expander { 0, ((void) As::id(), 0)... };
  • ... expands a pattern to its left; in this case the pattern is the expression ((void) As::id(), 0).

  • The , in the expression is the comma operator, which evaluates the first operand, discards the result, then evaluates the second operand, and returns the result.

  • The (void) cast on As::id() exists to guard against overloaded operator,, and can be omitted if you are sure that none of the As::id() calls will return something that overloads the comma operator.
  • 0 on the right hand side of the comma operator is because expander is an array of ints, so the whole expression (which is used to initialize an element of the array) must evaluate to an int.
  • The first 0 ensures that we don't attempt to create an illegal 0-sized array when As is an empty pack.

Demo.


In C++17 (if we are lucky), the entire body of C::id can be replaced with a binary fold expression: (A::id(), ... , (void) As::id()); Demo.

Expand parameter pack in calling the base types' methods when variadic template class is inherited from template arguments

To fix your solution, disable the second overload when parameter pack is empty:

template <typename U, typename... Us>
typename std::enable_if< (sizeof...(Us) > 0) >::type
call_methods()
{
U::method();
call_methods<Us...>();
}

Gets rid of ambiguity.

Live example.

How to expand parameter pack of base classes and call member function of each one?

There are only few contexts where pack-expansion can occur ([temp.variadic] / p5).

In c++11 and c++14 you can't create pack-expansion from a function call, but you can expand it i.e. within an array initializer-list:

void display()
{
using discard = int[];
(void)discard{ 0, ((void)WrapperType<Args>::wrapee_.display(), 1)... };
}

DEMO

In c++17 one can use fold-expressions:

void display()
{
(WrapperType<Args>::wrapee_.display(), ...);
}

DEMO 2

Variadic template base class call forwarding

This should work:

template<typename F, typename... T>
struct recinit;

template<typename F>
struct recinit<F> {
static bool tinit(F *) {
return true;
}
};
template<typename F, typename T, typename... G>
struct recinit<F, T, G...> {
static bool tinit(F *ptr) {
if (!ptr->T::init())
return false;
return recinit<F, G...>::tinit(ptr);
}
};

template<typename... Features>
struct Foo : Features... {

bool init() {
bool res = recinit<Foo, Features...>::tinit(this);
//use res wisely
}
};

Your problem is that you cannot write partial specializations of functions, only of classes/structs. And the auxiliary struct has to be outside of Foo or else it will get the template arguments from the enclosing struct, and that would be bad.

You don't say but I'm assuming that init is a non-static member function. If that is the case, the args arguments make little sense: all of them should be this! So just past this once and avoid the pack in the arguments. I tried passing this as a void* but that may be troublesome, so I just added an additional template argument to recinit that will be Foo.

And also, each time you do one recursive step remember to remove one parameter.

Expand variadic template to array of static members

For a vector, you just need

std::vector<int> values = { derived_from_bases::value... };

If you have C++17, you can get a std::array the same way like

std::array values = { derived_from_bases::value... };

and CTAD will deduce the type and size of the array for you. If you do not have C++17, then you can use

std::array<int, sizeof...(derived_from_bases)> values = { derived_from_bases::value... };

Multiple inheritance with variadic templates: how to call function for each base class?

One way to iterate over the variadic bases:

template <typename T, typename ...Args>
class ChildGenerator : public Args...
{
public:
ChildGenerator(T t) : Args(t)... {}

void doThings() override {
int dummy[] = {0, (Args::doThings(), void(), 0)...};
static_cast<void>(dummy); // avoid warning for unused variable
}
};

or in C++17, with folding expression:

    void doThings() override {
(static_cast<void>(Args::doThings()), ...);
}

C++ expand variadic template arguments into a statement

C++17 solution - fold expression:

template <typename... Ts>
auto anyCondition(Ts... xs)
{
return (xs || ...);
}

wandbox example


C++11 solution - for_each_argument:

template <typename TF, typename... Ts>
void for_each_argument(TF&& f, Ts&&... xs)
{
(void)(int[]){(f(std::forward<Ts>(xs)), 0)...};
}

template <typename... Ts>
auto anyCondition(Ts... xs)
{
bool acc = false;
for_each_argument([&acc](bool x){ acc = acc || x; }, xs...);
return acc;
}

wandbox example

I gave a talk about this snippet at CppCon 2015:

CppCon 2015: Vittorio Romeo “for_each_argument explained and expanded"

Call base class operator= from derived in parameter pack

You need to expand the parameter pack. How about a nice fold expression:

(Ts::operator=(other), ...);

This will expand Ts... and effectively create multiple calls to operator=, one for each type in the pack.

variadic template parameter pack expanding for function calls

Unfortunately, as you noticed, expanding a parameter pack is only valid in certain contexts where the parser expects a comma-separated list of entries – contexts where the comma is just a syntactic separator, not the comma operator. This is arguably a deficiency in the current text.

An ugly workaround:

func((some(p), 0)...);

Do note that the evaluation order of function arguments, and thus the order of the some invocations, is unspecified, so you have to be careful with any side effects.

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

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 e.g. 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 (i.e. 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.



Related Topics



Leave a reply



Submit