1

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> // // I am putting this general T type, to show it can be a large (movable) object, for example, std::vector.
struct wrapper{
   T a;
   operator T const&() const&{return a;}  // in other cases it can involve more code, like reinterpret_casts or some conditional blocks.
   operator T&&() &&{return std::move(a);} // same
   operator T&() &{return a;} // same
};

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

I could make it more general, (but longer code for this simple case) this way,

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

The final objective is that 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.

alfC
  • 10,293
  • 4
  • 42
  • 88

0 Answers0