C++ Logo

std-proposals

Advanced search

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

From: Jonathan Wakely <cxx_at_[hidden]>
Date: Thu, 28 Sep 2023 13:27:09 +0100
On Thu, 28 Sept 2023 at 11:50, Frederick Virchanza Gotham via Std-Proposals
<std-proposals_at_[hidden]> wrote:

> 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";
> }
> }
>

whythough.jpg

Received on 2023-09-28 12:27:23