gpt4 book ai didi

c++ - 通过包装对象上的函数指针调用类方法时出错

转载 作者:行者123 更新时间:2023-11-30 03:49:44 25 4
gpt4 key购买 nike

我来自 C 背景并且是 CPP 的新手。我有一种情况,我需要在一个将修改对象的对象上调用一个方法。但是从方法返回时,我需要将对象恢复到之前的状态。为实现这一点,我使用了“Bjarne Stroustrup”展示的后缀、前缀包装器技术。

除了这种技术,我还尝试使用函数模板和函数指针来概括将在修改后的对象上调用的方法。

template < class T >
class Call_proxy {
T* obj;
int ID;
public:
Call_proxy( T* pp ) : obj( pp ), ID( i ) {
}

~Call_proxy() {
obj->setID( ID );
}

T* operator ->() {
return obj;
}
};

template < class T >
class Proxy {
T* obj;
int ID;
public:
Proxy(T* pp) : obj(pp), ID(pp->getID()) { }

Call_proxy<T> operator ->() {
return Call_proxy<T>( obj, ID );
}
};

class X
{
int id;
public:
int getID();
void setID(int ID) { id = ID; }
void somefunction(int, int);
};

template<class X>
void doSomething(int nu, void(X::*fcn)(int, int))
{
Proxy<X> P(x);
P->setID(nu);
(P->*fcn)(nu, 1); //This call generates error on VS2010: Error 1 error C2296: '->*' : illegal, left operand has type 'Proxy<T>'
}

int main()
{
X x;
doSomething<X>(1, &X::somefunction);
}

你能帮我理解 VS2010 一直提示 (P->*fcn)(nu, 1); 构造吗?

最佳答案

来自 [expr.mptr.oper]:

The binary operator ->* binds its second operand, which shall be of type “pointer to member of T” to its first operand, which shall be of type “pointer to U” where U is either T or a class of which T is an unambiguous and accessible base class. The expression E1->*E2 is converted into the equivalent form (*(E1)).*E2.

尽管Proxy<T>operator ->()实现,没关系,因为:

(P->*fcn)(nu, 1);

不会使用 operator -> .根据语法,它是特殊的。您只能调用fcn在指向 X 的指针上(或源自 X 的东西)。

关于c++ - 通过包装对象上的函数指针调用类方法时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32260570/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com