lundi 26 septembre 2016

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 Foo with arbitrary attributes into another Foo with arbitrary attributes. Attributes associated with both Foos should be copied. However, I have no idea how to implement it.

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

Aucun commentaire:

Enregistrer un commentaire