2016-09-22 57 views
2

免責聲明:這絕不意味着在生產代碼中使用。這是一個探索在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());

+5

我不知道任何答案,這可能永遠是「優雅」 。 –

+2

優雅的是讓你想從外部訪問的成員'公共'而不是'私人' – user463035818

+0

主要是什麼'b'? –

回答

1

你是幾乎沒有。下面是你應該寫什麼:

typedef int (A::*pf)(); 
const pf func = get(A_access_f()); 
int a = (sut.*func)(); 

或者作爲(難以消化)的一行:

int a = (sut.*get(A_access_f()))(); 
+0

有趣的是,我也在玩弄單線式的風格,但遭受了正確的語法。 – mrAtari

相關問題