vendredi 24 avril 2015

Abstraction over single c++ object and std::pair of objects using templates

Assume the following template construction:

enum class ENUM {SINGLE, PAIR};
// General data type
template<ENUM T, class U>class Data;
// Partially specialized for single objects
template<class U>Data<ENUM::SINGLE, U> : public U {
  // Forward Constructors, ...
};
// Partially specialized for pairs of objects
template<class U>Data<ENUM::PAIR, U> : public std::pair<U,U> {
  // Forward Constructors, ...
};

In my code I want to be able to write something like

template<ENUM T>someMethod(Data<T, int> data) {
  for_single_or_pair {
    ++data;
  }
}

which does the same as the combination of the following methods:

template<>someMethod(Data<ENUM::SINGLE, int> data) {
  ++data;
  // Or something else happens with data
}

template<>someMethod(Data<ENUM::PAIR, int> data) {
  ++data.first;
  ++data.second;
  /*
   * Other things that were done with data in the SINGLE method
   * should happen here with data.first and data.second.
   */
}

The syntax of the solution may be very different from what I wrote above, this is just to demonstrate what I want to achieve. I would prefer a solution without macros, but could also live with that.

Can such an abstraction be realized in C++11?

Aucun commentaire:

Enregistrer un commentaire