2016-09-22 59 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

相关问题