C++ Logo

std-proposals

Advanced search

[std-proposals] Let constructor know if object is const or volatile

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Thu, 28 Sep 2023 11:50:14 +0100
Consider the following code snippet:

#include <iostream> // cout, endl
#include <type_traits> // is_const, remove_pointer

struct Monkey {
    int i;
    void NonConst(void) { i = 7; }
    Monkey(void)
    {
        this->NonConst(); // 'this' must be a pointer to non-const here

        if ( std::is_const_v< std::remove_pointer_t<decltype(this)> > )
        {
            std::cout << "This is a const object\n";
        }
    }
};

int main(void)
{
    Monkey obj1;
    Monkey const obj2;
}

This code snippet doesn't print "This is a const object" because
'this' is a pointer to non-const inside the constructor.

Perhaps we could have an implicit type inside every constructor,
something like "_This_t" to be used as followed:

    Monkey::Monkey(void)
    {
        this->NonConst(); // 'this' must be a pointer to non-const here

        if ( std::is_const_v< std::remove_pointer_t<_This_t> > )
        {
            std::cout << "This is a const object\n";
        }
    }

Received on 2023-09-28 10:50:28