Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 搜索一种优雅且非侵入性的方式来访问类的私有方法_C++_Templates_Template Meta Programming - Fatal编程技术网

C++ 搜索一种优雅且非侵入性的方式来访问类的私有方法

C++ 搜索一种优雅且非侵入性的方式来访问类的私有方法,c++,templates,template-meta-programming,C++,Templates,Template Meta Programming,免责声明:这绝不意味着要在生产代码中使用。在C++的边上进行探索: 我的问题是基于与@Johannes Schaub的讨论而提出的后续问题: 我在他的博客上找到了一个非常简短的私人会员访问解决方案: 以下是一个示例: #include <iostream> using namespace std; // example class struct A { A(int a, double b):_a(a),_b(b) { } private: int _a; doubl

免责声明:这绝不意味着要在生产代码中使用。在C++的边上进行探索:

我的问题是基于与@Johannes Schaub的讨论而提出的后续问题:

我在他的博客上找到了一个非常简短的私人会员访问解决方案:

以下是一个示例:

#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;
}
我的编译器仍在抱怨:

程序cpp:45:33:错误:非静态成员函数的使用无效 pf func=sut.*获取(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()))();

我不确定这个问题的答案是否“优雅”。优雅是让你想从外部访问的成员
public
,而不是
private
在main中
b
是什么?@Martin Bonner:但它不是compileI在主样本中的意思,然后意识到你的主样本是访问成员变量,不是成员函数有趣,我也在玩单行程序样式,但是遇到了正确语法的问题。
typedef int (A::*pf)();
const pf func = get(A_access_f());
int a = (sut.*func)();
int a = (sut.*get(A_access_f()))();