user1494080 user1494080 - 1 year ago 86
C++ Question

How to convert between different instantiations of the same variadic template?

Assume we have a data structure Foo that maintains a set of elements. It should be possible to associate attributes with the elements as needed. The attributes should be stored in a separate vector each. We implement this by means of variadic templates:

#include <vector>

template <typename ...Attrs>
struct Foo : public Attrs... {
Foo(int n = 0) {
using PackExpansionT = int[];
PackExpansionT{0, (Attrs::values.resize(n), 0)...};

struct AttrA { std::vector<int> values; };
struct AttrB { std::vector<float> values; };
struct AttrC { std::vector<double> values; };

int main() {
Foo<AttrA, AttrB> foo; // Maintains set of elements with two attributes each.

Now, I want a conversion operator with the following semantics:

Foo<AttrB, AttrC> bar = foo; // bar.AttrB::values should be a copy of foo.AttrB::values.

This is only an example. In general, the conversion operator should be able to convert a
with arbitrary attributes into another Foo with arbitrary attributes. Attributes associated with both
s should be copied. Attributes not associated with both can be left defaulted. However, I have no idea how to implement it.

template <typename ...OthersAttrs>
operator Foo<OthersAttrs...>() const {
// ...?

Answer Source

We can just make a bunch of independent decisions. First, let's add a constructor so that we can construct Foo from its attribute constituents:

Foo(Attrs const&... attrs)
: Attrs(attrs)...
{ }

Next, for each attribute in Others, we will either downcast this to the appropriate type if possible or return a default-constructed one otherwise:

template <typename... Others>
operator Foo<Others...>() const {
    return {get_attr<Others>(this)...};


template <class T>
T const& get_attr(T const* v) const {
    return *v;

template <class T>
T get_attr(...) const {
    return T{};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download