carlo
carlo

Reputation: 355

How can I detect if the instance is const from a member function?

I would like to write a member function which detects if the instantiated object is const.

To give a simple example, we can consider the following class definition

class Foo{
  public:
    void constnessChecker(){
      bool isConst;
      // MORE CODE GOES HERE...
      if (isConst) {
        std::cout << "This instance is const! << std::endl;
      } else {
        std::cout << "This instance is not const! << std::endl;
      }
    }
};

and the following code

int main(){
  Foo foo1;
  Foo const foo2;
  foo1.constnessChecker();
  foo2.constnessChecker();
}

which should produce

This instance is not const!
This instance is const!

Is this possible?

Upvotes: 2

Views: 410

Answers (2)

thokra
thokra

Reputation: 2904

In the style of boost::is_const or std::is_const, you can also write up the following:

#include <iostream>

template <typename T>
struct is_const
{
  static const bool value = false;
};

template <typename T>
struct is_const<const T*>
{
  static const bool value = true;
};

struct S
{
  void f() const
  {
    std::cout << is_const<decltype(this)>::value << std::endl;
  }

  void f()
  {
    std::cout << is_const<decltype(this)>::value << std::endl;
  }

  int m;
};

int main(int argc, char** argv)
{
  const S& cs = S(); // note that choosing a const-ref is merely to force the compiler to choos S::f() const!
  cs.f ();  // prints 1

  S().f (); // prints 0

  return 0;
}

I haven't looked at the implementation of std::is_const but for some reason it returns false where the above is_const returns true.

Note: Obviously you need support for decltype and thus the above will only work for C++11 compliant compilers.

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227438

Provide const and non-const overloads:

class Foo
{
  public:
    void constnessChecker(){
      std::cout << "This instance is not const\n";
    }
    void constnessChecker() const {
      std::cout << "This instance is const\n";
    }

....
};

Upvotes: 12

Related Questions