I want to write a pointer in c++ (or in c++0x), that will points to a operator of a class lets say A or B. Is there any method to do it?
Of course there is a syntax like
int (A::*_p) ();
but it doesn't solve this problem. I want to make general pointer, not specifying the base class for it - only pointer for "operator function"
#include <thread>
#include <iostream>
using namespace std;
class A
{
public:
int operator()()
{
return 10;
}
};
class B
{
public:
int operator()()
{
return 11;
}
};
int main()
{
A a;
int (*_p) ();
_p = a.operator();
cout << _p();
B b;
_p = b.operator();
cout << _p();
}
No, you can't do this. The class type is a part of the type of the operator member function.
The type of A::operator()()
is different from the type of B::operator()()
. The former is of type int (A::*)()
while the latter is of type int (B::*)()
. Those types are entirely unrelated.
The closest you can get is by using something like the C++0x polymorphic function wrapper function
(found in C++0x, C++ TR1, and Boost) and by using bind
to bind the member function pointer to a class instance:
std::function<int()> _p;
A a;
_p = std::bind(&A::operator(), a);
std::cout << _p();
B b;
_p = std::bind(&B::operator(), b);
std::cout << _p();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With