免责声明:决不能在生产代码中使用。这是C++边缘的探索:)

我的问题是根据与@Johannes Schaub进行的讨论在这里进行跟进:
calling private methods in c++

我在他的博客上找到了一个非常简单的私有(private)成员访问解决方案:
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;
}

我想知道是否可以重用这种非常优雅的方法从类外部访问私有(private)方法。

我想拥有的是与方法调用相同的简单方法:
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());

我的编译器仍在抱怨:

最佳答案

你快到了这是您应该写的:

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

或作为(难以消化的)一线客:
int a = (sut.*get(A_access_f()))();

关于c++ - 搜索一种优雅且非侵入式的方法来访问类的私有(private)方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39648419/

10-14 18:45
查看更多