Skip to content

Instantly share code, notes, and snippets.

@10110111
Created December 18, 2017 19:47
Show Gist options
  • Save 10110111/4ad0fd5a092200e454fa06f09963e63d to your computer and use it in GitHub Desktop.
Save 10110111/4ad0fd5a092200e454fa06f09963e63d to your computer and use it in GitHub Desktop.
An example of legally getting access to private members in C++
// The code below demonstrates how to access private members without changing
// the class. It's useful for e.g. debugging when you for some reason can't
// change a library class, but need to have some private values printed.
// Original idea by litb, see
// http://bloglitb.blogspot.com/2010/07/access-to-private-members-thats-easy.html
template<typename Pointer>
struct RobberyResult
{
static Pointer ptr;
};
template<typename Pointer> Pointer RobberyResult<Pointer>::ptr;
template<typename Pointer, Pointer p>
struct Rob : RobberyResult<Pointer>
{
struct Filler
{
Filler()
{
RobberyResult<Pointer>::ptr=p;
}
};
static Filler filler;
};
template<typename Pointer, Pointer p> typename Rob<Pointer,p>::Filler Rob<Pointer,p>::filler;
#define STEAL_CLASS_MEMBER(member) template class Rob<decltype(&member), &member>
// ---------------- usage below ------------------------------------
#include <iostream>
class Victim
{
int treasure=7;
double privilegedAction(int x) { return treasure*0.14+x; }
};
STEAL_CLASS_MEMBER(Victim::treasure);
STEAL_CLASS_MEMBER(Victim::privilegedAction);
int main()
{
Victim victim;
std::cout << "treasure: " << victim.*RobberyResult<int Victim::*>::ptr << "\n";
std::cout << "privileged result: " << (victim.*RobberyResult<double (Victim::*)(int)>::ptr)(23) << "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment