So you are asking for a way to know at runtime inside a constructor, whether the constructed object is const or non-const?

Like an implicit parameter? Not ABI compatible, performance cost.

 

Or at compile-time? Then the constructor would have to be a template to generate two functions.

 

It is not supported by the current standard.

 

 

As alternative you could use two different factory functions instead.


 

-----Ursprüngliche Nachricht-----
Von: Frederick Virchanza Gotham via Std-Proposals <std-proposals@lists.isocpp.org>
Gesendet: Do 28.09.2023 12:50
Betreff: [std-proposals] Let constructor know if object is const or volatile
An: std-proposals <std-proposals@lists.isocpp.org>;
CC: Frederick Virchanza Gotham <cauldwell.thomas@gmail.com>;
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";
       }
   }
--
Std-Proposals mailing list
Std-Proposals@lists.isocpp.org
https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals