Search code examples
c++templatesconstantsreinterpret-cast

reinterpret_cast a template class to const version


AFAIK, a template class with template argument <Type> is completely distinct from <const Type>.

template<typename T>
struct Wrapper
{
  T obj = T{};

  //other code 
};

Now I can't pass Wrapper<int>& to a function that needs Wrapper<const int>&.

void someFunc(Wrapper<const int>& wrapper);
//...
Wrapper<int> wrapper;
someFunc(wrapper); //error

What can go wrong by reinterpret_cast'ing it to its const version?

operator Wrapper<const T>&() { return *(reinterpret_cast<Wrapper<const T>*>(this)); }

Adding the above line to Wrapper makes it work without having to create a new <const int> object. obj can't be accessed inside the function, so it should not matter if the passed parameter is actually <const Type> or <Type>.

Provided there is no template specialization, can anything go wrong here (as far as standard goes vs in practice)?


Solution

  • There is a number of optimizations that can be different between the const and non-const cases, meaning both the memory layout of the class (e.g. since const objects does not need to actually exist) and the usage of the class can be different.

    In other words: Using reinterpret_cast for this can result in unexpected behaviour and should not be done.

    In my opinion there are several ways where over-eager usage of the const keyword can result in more complicated code without any gain, and this is one of them.
    I suggest avoiding the <const Type> cases instead of trying to handle them.

    Without knowing the use case, it seems to me most use cases would be covered by using const Wrapper<T> instead of Wrapper<const T>.