c++ crtp for adapter: pass threw temporary return value

  adapter, c++, crtp

The following simple code snipped does not compile with the following compiler message:

binding reference of type 'int' to value of type 'const int' drops 'const' qualifier
        > return m;

Code Snippet:

class Base {
    public:
    int& ref() const {
        return m;
    }

    private:
    int m = 0;
};

template <typename Base>
class Final {
    public:
    int& ref() const {
        return b.ref();
    }

    private:
    Base b;
};

I do believe that’s because the return value of Base::ref in the Final class instantiation is a temporary reference and thus implicit casted to a const int reference.
But how would I pass threw the return type of the Base implementation without const casting.
Is a temporary object needed for every passthrew if multiple adapters like this one are in use?

PS: I know that one should not return references to member variables. This is just a simple example. The actual pattern is used for Iterator Adapters.

Source: Windows Questions C++

LEAVE A COMMENT