我需要调用某些类的实例的私有方法,
我使用了一个小的代码片段,如果成员没有重载,它可以正常工作,否则它会失败,解决方案是什么以及如何提供重载成员函数的地址?
templates.h
template <class ClassT>
struct AddressHolder
{
static typename ClassT::PtrPrivateMemFnT address;
};
// init static member
template <class ClassT>
typename ClassT::PtrPrivateMemFnT AddressHolder<ClassT>::address = 0;
template <class ClassT, typename ClassT::PtrPrivateMemFnT x>
struct GetAddress
{
GetAddress() { AddressHolder<ClassT>::address = x; }
static GetAddress instance;
};
template <class ClassT, typename ClassT::PtrPrivateMemFnT x>
GetAddress<ClassT,x> GetAddress<ClassT,x>::instance;
的main.cpp
#include "templates.h"
class HidenGems {
void privateMethod() {std::cout << "hey1\n";}
void privateMethod2(int) {std::cout << "hey2\n";}
void privateMethod2(int,int) {std::cout << "hey2\n";}
};
struct PrivateMethod_TypeHolder {
typedef void(HidenGems::*PtrPrivateMemFnT)();
};
struct PrivateMethod2_TypeHolder {
typedef void(HidenGems::*PtrPrivateMemFnT)(int);
};
struct PrivateMethod2_int_int_TypeHolder {
typedef void(HidenGems::*PtrPrivateMemFnT)(int,int);
};
template struct GetAddress<PrivateMethod_TypeHolder, &HidenGems::privateMethod>;
template class GetAddress<PrivateMethod2_TypeHolder, &HidenGems::privateMethod2>;
template class GetAddress<PrivateMethod2_int_int_TypeHolder, &HidenGems::privateMethod2>;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
HidenGems hg;
(hg.*AddressHolder<PrivateMethod_TypeHolder>::address)();
(hg.*AddressHolder<PrivateMethod2_TypeHolder>::address)(100);
(hg.*AddressHolder<PrivateMethod2_int_int_TypeHolder>::address)(100,100);
return a.exec();
}
我收到了编译信息:
/Users/mac/dummy/main.cpp:29: error: 'privateMethod2' is a private member of 'HidenGems'
template class GetAddress<PrivateMethod2_TypeHolder, &HidenGems::privateMethod2>;
/Users/mac/dummy/main.cpp:30: error: 'privateMethod2' is a private member of 'HidenGems'
template class GetAddress<PrivateMethod2_int_int_TypeHolder, &HidenGems::privateMethod2>;