搜索一个优雅和非侵入性的方式来访问类的私有方法 [英] Search for an elegant and nonintrusive way to access private methods of a class

查看:107
本文介绍了搜索一个优雅和非侵入性的方式来访问类的私有方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

免责声明:这绝不意味着在生产代码中使用。这是一个在C ++边缘的探索:)

Disclaimer: This is never meant to be used in production code. It's an exploration at the edges of C++ :)

我的问题是一个跟进,基于与@Johannes Schaub的讨论:
在c ++中调用私有方法

My question is a follow up, based on a discussion with @Johannes Schaub here: calling private methods in c++.

I在他的博客中找到了一个非常短的私人成员访问解决方案:
http://bloglitb.blogspot.de/2011/12/access-to-private-members-safer.html

I found a very short solution for private member access on his blog: 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;
}

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

I wondered if this very elegant approach can be reused to access private methods from outside of a class.

我想要的是一个方法调用的简单方法:

What I would like to have, is the same simple approach for a method call:

struct A_access_f
{
    typedef int (A::*type)();
    friend type get(A_access_f);
};
template struct Rob<A_access_f, &A::f>;

是否可以运行?

这是我现在最好的尝试:

This is my best attempt till now:

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

我的编译器仍然抱怨:


prog.cpp:45:33:错误:无效使用非静态成员函数
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());


推荐答案

你几乎在那里。这里是你应该写的:

You were almost there. Here is what you should have written:

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

或作为(难以摘要)单行:

Or as a (hard-to-digest) one-liner:

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

这篇关于搜索一个优雅和非侵入性的方式来访问类的私有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆