Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast const member function to non-const

Is casting the constness of member function pointers defined in C++? Is the following valid code?

struct T {
  void foo(int i) const { std::cout << i << std::endl;};
};

void (T::*f1)(int) const = &T::foo;
void (T::*f2)(int)       = reinterpret_cast<void (T::*)(int)>(f1);
T t;
(t.*f2)(1);

Update:

The reason why I need this is that I'm writing a function that accepts both an object and a member function pointer to that object. I need a version for const objects (accepting only const functions) and a normal one. Since I don't want duplicate code, my idea was to put the actual code in the non-const version and call it from the const one, casting away any consts.

like image 463
lucas clemente Avatar asked Oct 23 '22 13:10

lucas clemente


1 Answers

Compiler eats it. But the backward cast is more useful.

And again but - it is better to don't use it, const_cast is usually just a quick and dirty solution, which you apply only when there are not any other solution.

Answer to update

If I understand you correctly you are going to use one object and two function. First function accepts const object and const member-function, second - non-const object and non-const member-function.

According to given information you can change second function to accept non-const object and const member-function. And give them one non-const object and its const member-function.

like image 123
klm123 Avatar answered Oct 27 '22 11:10

klm123