keanehui
keanehui

Reputation: 195

Specification of use of overloaded function

template <typename T>
class Obj {
public:
Obj<T>* doThis();
const Obj<T>* doThis() const {// return normal version of doThis()}
};

In the example, I want the const version of doThis() to return normal version of doThis(). I don't think it's ok to just put return doThis() in definition of const version of doThis() because C++ may think this is recursion of const version of doThis().

Is there any way to explicitly tell C++ which function to call?

Upvotes: 0

Views: 36

Answers (1)

Holt
Holt

Reputation: 37626

As Story Teller mentioned in the comment, don't do this, because this can lead to UB, e.g., in this simple case:

const Obj<int> obj;
obj.doThis(); // UB since you will have to const_cast<Obj<int>&>(obj).

The proper thing is to do it the other way:

template <typename T>
class Obj {
public:
    Obj<T>* doThis() {
        return const_cast<Obj<T>*>(std::as_const(*this).doThis());
    }
    const Obj<T>* doThis() const { /* Actual implementation. */ }
};

Note that this implies that the return value of doThis() const can be safely const_cast back to Obj<T>* (e.g., if you return this in doThis, this is safe).

If you cannot implement doThis() in the const-qualified version, then your code is probably flawed.

Upvotes: 2

Related Questions