vendredi 31 mai 2019

In a non-const member function, why is point this non-const, while decltype pointer this is const?

I have a heavily templated class from which I want to use a getter. Following a common convention, I've avoided code duplication like so:

template< typename Foo, typename... Bars >
class Templated
{
...

  constexpr const Foo& get() const 
  { 
    return mFoo;
  }

  constexpr Foo& get() 
  { 
    return const_cast<Foo&>(const_cast<const Templated<Foo, Bars...> *>(this)->get());
  }

However it occurred to me that the second definition gets a bit clunky, especially with a class that has many template parameters. Luckily I figured out after a little messing around that I could simplify this for any generic class template to:

constexpr Foo& get()
{
  return const_cast<Foo&>(const_cast<decltype(this)>(this)->get());

This works because, for some reason, decltype(this) resolves to a const pointer to the class object type, whereas just (this) resolves to a non-const pointer to the class object type. Why in the world is this the case?

Aucun commentaire:

Enregistrer un commentaire