0

You are given a variable p defined in C++ program. Is it possible to find out if it's a pointer to something or a normal variable? specifically, suppose there is a class Test

    class Test
    {
    public:
        int test1(int i)
        {
            
        }
        static int test2(int i)
        {
        }
const int test3(int i)
    {
    }

}

Now `this` is a variable accessible inside test1 and test2 and test3, But I want to determine the type of `this` inside each of these functions. It could be `Test,` `Test const,` `Test* const` etc...
How can I figure this out myself, or is there any alternate documentation for the same?
Botje
  • 26,269
  • 3
  • 31
  • 41
daniel
  • 369
  • 2
  • 10
  • And what would you _do_ with this information, exactly? That will help us help you. – Botje Nov 10 '21 at 13:35
  • `this` is a pointer to the calling object. The member function doesn't affect it at all. – sweenish Nov 10 '21 at 13:36
  • 1
    Note that `this` is *not* accessible in `test2` -- `test2` is a static member. – G.M. Nov 10 '21 at 13:38
  • A first hint is that you may look at type_traits "https://en.cppreference.com/w/cpp/header/type_traits" or here: https://en.cppreference.com/w/cpp/types – A M Nov 10 '21 at 13:39
  • In the question's code, the simple answer is to glance at the function declaration and you'll immediately know from that with some fundamental C++ knowledge. If the real problem is more complicated to the point where that won't work, it's helpful to give a little more context. – chris Nov 10 '21 at 13:43
  • FYI: [SO: Type of 'this' pointer](https://stackoverflow.com/q/6067244/7478597) – Scheff's Cat Nov 10 '21 at 13:48
  • If the nonstatic member function is declared const, then the `this` pointer is pointing to a const object. Likewise, if the nonstatic member function is not declared const, then the `this` pointer points to a non-const. There is no checking necessary, just look at your function signature and you know. static members do not have any `this` poitner. – Chris Uzdavinis Nov 10 '21 at 13:59

1 Answers1

1

You can use, having written #include<type_traits>

std::is_const<decltype(this)>::value

within a member function. If that member function is const then this value will be true, else it will be false.

Note there is no this in a static member function, and that this is always a pointer type in C++.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Thanks. So I understand that this will always be a pointer type in C++, But could it be a `const` pointer? – daniel Nov 10 '21 at 14:11
  • @daniel -- `this` is **always** a `const` pointer; you cannot modify its value. You're right that `this` can point at a `const` object or at a non-`const` object. – Pete Becker Nov 10 '21 at 14:13