寻找一种优雅且非侵入性的方式来访问类的私有方法
Search for an elegant and nonintrusive way to access private methods of a class
免责声明:这绝不意味着在生产代码中使用。这是对c++边缘的一次探索:)
我的问题是一个后续问题,基于与@Johannes Schaub的讨论: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:错误:无效使用非静态成员函数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()))();
相关文章:
- VS2017 是否更改了 C++ 中访问 C# 命名空间的方式?
- C++:使用 std::unique_ptr 访问重载运算符++的最佳方式?
- 以这种方式在运行时访问元组的性能成本
- 如何以简洁的方式安全地访问容器中的每个第 n 个元素?
- 访问 std::multimap 值的最佳方式?
- C++ Windows - 以编程方式检查软件是否访问互联网?
- 以类似数组的方式访问结构成员:在与数组不同的结构中填充?
- 确定范围是访问虚拟功能的合法方式吗?
- 如何在CPP中以最快的方式对HTML访问日志进行分类
- 如何通过 Windows SDK 以编程方式访问"netsh"API
- 访问"std::variant"的不安全、"noexcept"和无开销方式
- 如何以这种方式访问另一个文件的方法/函数
- 如何以编程方式访问c/c++a-la-rdtsc中的性能计数器
- 如何使C++类以 const 方式访问另一个类的所有私有成员(仅读取而不写入)
- 为什么以这种方式访问联合中的指针会导致分段错误?
- 如何遍历boost::fusion关联结构并以通用方式访问键
- 为什么SDL不加载我的图像时,主应用程序通过快捷方式访问
- c++以多种方式访问相同的元素
- 以原子方式访问存储在映射中的资源
- 如果需要,我将如何以编程方式访问或打开交换 edb 文件