dimanche 1 octobre 2017

Conversion operator overloads for l-values, avoid repeated code

I have a wrapper class that needs to be used interchangeably with the wrapped class. Fortunately the class and the wrapper are binary compatible (by design) and the conversion can be easily performed (for example in this case by reinterpret_cast, or even simpler as in the example).

In part, to achieve this, I need to be able to convert from the wrapper type to the wrapped type, via operator T().

Currently the code looks like this:

template<class T>
struct A{T val_;}; // I am putting this general T type, to show it can be a large (movable) object, for example, std::vector.

template<class T>
struct wrapper{
   A<T> a;
   operator A<T> const&() const&{return a;}  // in other cases it can involve more code, like reinterpret_casts or some conditional blocks.
   operator A<T>&&() &&{return std::move(a);} // same
   operator A<T>&() &{return a;} // same
};

Can I condense these three conversion functions into one function/less code, or is there another way?

I could make it more general, (but longer code for this single case) this way, but this is about it.

template<class T>
struct wrapper{
   A<T> a;
   operator A const&() const&{return a;} // complicated code can be here only
   operator A&&() &&{return std::move(operator A&());}
   operator A&() &{return const_cast<A&>(operator A const&());}
};

The final objective is that A<T> can be used interchangeably with wrapper<T>.

This is very similar to How do I remove code duplication between similar const and non-const member functions?, however this case is more specific because 1) it involves the conversion operator and also, 2) involves l-value overloads.

Aucun commentaire:

Enregistrer un commentaire