0
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?

3
  • Don't. The const means something here. It's a promise that the object will not be modified during the invocation of the function. If you call the non-const version you'll potentially break this promise. That can only cause problems. Commented May 17, 2020 at 9:52
  • 2
    Now, if you want to do it the other way around, i.e. make the non-const overload call the const one, that would be fine and won't break any promises. Commented May 17, 2020 at 9:53
  • 1
    Of course there is a way. I was commenting on the direction you wish to do the code sharing. One is error prone, the other is much less so. Commented May 17, 2020 at 9:59

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.