免责声明:这绝不意味着在生产代码中使用。这是对 C++ 边缘的探索:)
我的问题是一个后续问题,基于与@Johannes Schaub 的讨论:在c++中调用私有方法 https://stackoverflow.com/questions/6873138/calling-private-method-in-c.
我在他的博客上找到了一个非常简短的私人会员访问解决方案:http://bloglitb.blogspot.de/2011/12/access-to-private-members-safer.html http://bloglitb.blogspot.de/2011/12/access-to-private-members-safer.html
这是一个示例:
#include <iostream>
using namespace std;
// example class
struct A {
A(int a, double b):_a(a),_b(b) { }
private:
int _a;
double _b;
int f() { return _a; }
public:
};
//Robber template: provides a legal way to access a member
template<typename Tag, typename Tag::type M>
struct Rob {
friend typename Tag::type get(Tag) {
return M;
}
};
// tag used to access A::_a
struct A_access_a
{
typedef int A::*type;
friend type get(A_access_a);
};
// Explicit instantiation; the only place where it is legal to pass the address of a private member.
template struct Rob<A_access_a, &A::_a>;
int main() {
A sut(42, 2.2);
int a = sut.*get(A_access_a());
cout << a << endl;
return 0;
}
我想知道是否可以重用这种非常优雅的方法来从类外部访问私有方法。
我想要的是方法调用的相同简单方法:
struct A_access_f
{
typedef int (A::*type)();
friend type get(A_access_f);
};
template struct Rob<A_access_f, &A::f>;
有可能让它运行吗?
这是我迄今为止最好的尝试:
typedef int (A::*pf)();
pf func = sut.*get(A_access_f());
我的编译器仍然抱怨:
prog.cpp:45:33: 错误:非静态成员函数的使用无效
pf func = sut.*get(A_access_f());