c ++指针 [英] c++ pointers to operators
问题描述
我有一个问题。我想在c ++(或在c ++ 0x)中写一个指针,这将指向一个操作符af类让我们说A或B.
有任何方法吗?
I've got a problem. I want to write a pointer in c++ (or in c++0x), that will points to a operator af class lets say A or B. Is there any method to do it?
当然有一个语法如
int (A::*_p) ();
但它不能解决这个问题。我想要一般的指针,不要指定它的基类 - 只有操作符功能的指针
but it doesn't solve this problem. I want to make general pointer, not specyfing 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.
A :: operator()()
与 B :: operator()()
的类型不同。前者是 int(A :: *)()
类型,而后者是 int(B :: *)()
。这些类型是完全不相关的。
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.
你可以得到的最接近的是使用像C ++ 0x多态函数包装函数 function
(在C ++ 0x,C ++ TR1和Boost中找到),并使用 bind
将成员函数指针绑定到类实例:
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();
这篇关于c ++指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!