Created
February 2, 2017 01:40
-
-
Save mdadams/98710ba3478f306633df20dca47d5cd9 to your computer and use it in GitHub Desktop.
An example of private member access without friendship in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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