免責聲明:這絕不意味着在生產代碼中使用。這是一個探索在C++的邊緣:)尋找一種優雅和非侵入性的方式來訪問一個類的私有方法
我的問題是後續,根據與@Johannes Schaub在這裏討論: calling private methods in c++。
我發現在他的博客私有成員訪問很短的解決方案: 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: error: invalid use of non-static member function pf func = sut.*get(A_access_f());
我不知道任何答案,這可能永遠是「優雅」 。 –
優雅的是讓你想從外部訪問的成員'公共'而不是'私人' – user463035818
主要是什麼'b'? –