[英]c++ pointers to operators
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? 我想用c ++(或c ++ 0x)编写一个指针,指向一个类的运算符,让我们说A或B.有什么方法可以做到吗?
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()()
. A::operator()()
的类型与B::operator()()
的类型不同。 The former is of type int (A::*)()
while the latter is of type int (B::*)()
. 前者的类型为
int (A::*)()
而后者的类型为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: 最接近的是使用类似C ++ 0x多态函数包装
function
(在C ++ 0x,C ++ TR1和Boost中找到)并使用bind
将成员函数指针bind
到类实例:
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.