Skip to content

Instantly share code, notes, and snippets.

@mdadams
Created February 2, 2017 01:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdadams/98710ba3478f306633df20dca47d5cd9 to your computer and use it in GitHub Desktop.
Save mdadams/98710ba3478f306633df20dca47d5cd9 to your computer and use it in GitHub Desktop.
An example of private member access without friendship in C++
// This example is a variation on the code posted by Dave Abrahams at:
// https://gist.github.com/1528856.
#include <iostream>
template <typename Tag>
typename Tag::type saved_private_v;
template <typename Tag, typename Tag::type x>
bool save_private_v = (saved_private_v<Tag> = x);
class Widget {
public:
Widget(int i) : i_(i) {}
private:
int i_;
int f_() const {return i_;}
};
struct Widget_i_ {using type = int Widget::*;};
struct Widget_f_ {using type = int (Widget::*)() const;};
template bool save_private_v<Widget_i_, &Widget::i_>;
template bool save_private_v<Widget_f_, &Widget::f_>;
int main() {
Widget w(42);
std::cout << w.*saved_private_v<Widget_i_> << '\n';
std::cout << (w.*saved_private_v<Widget_f_>)() << '\n';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment