#StackBounty: #c++ #const #type-deduction Type of member variables in a const member function

Bounty: 400

When I have a member function marked as const and inspect the types of the member variables I get some results I don’t expect.

#include <iostream>
#include <string>

template<typename T>
struct type_printer;

class const_type_test {
public:
    void test() const {
        type_printer<decltype(value)> _;
    }
    int& test2() const {
        return value;
    }
    void test3() const {
        auto& x = value;
        type_printer<decltype(x)> _;
    }
    void test4() const {
        auto* x = &value;
        type_printer<decltype(*x)> _;
    }
private:
    int value;
};

int main(int argc, char** argv) 
{
    const const_type_test x;

    return 0;
}

My understanding is that when you are in a const method the method is effectively some name mangled name then they parameter type is classname const* const. I always thought that in the const method scope the member variables are effectively const, i.e. value would be const int. However when using the compiler error to deduce the types I get types I don’t expect.

The error output for void const_type_test::test() const: aggregate type_printer<int> _ has incomplete type and cannot be defined, type_printer<decltype(value)> _;

So I am seeing the type was deduced as int. I thought it would be const int as you can not change the value. Am I using decltype wrong? Or have I a hole in my understanding.

The reason I guess for asking is that in test2 the compiler complains: binding reference of type int& to const int discards qualifiers. Which is exactly what I expect. Can bind a const reference to non const reference.

Example 3 shows the following error: error: aggregate type_printer<const int&> _ has incomplete type and cannot be defined type_printer<decltype(x)> _. Which is what I expect it has been deduced as a const reference.

Example 4: deduces also a type_printer<const int&> which I thought would be a pointer.

Keen to get some reference to the standard to find out where the holes in my knowledge are. I am also wondering if there are some weird type deduction rules when using decltype that are tripping me up.


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.