Jun 7, 2017

[C++] hijack private data member through template instantiation.


Resize string/vector without initialization

discuss:
Uses and Abuses of Access Rights

it works because explicit template instantiation ignores access restrictions, and the friend definition "leaks" the templated type out of the class, without having to write it anywhere..

code:
#include <iostream>

class A {
private:
  void f(int) { std::cout << "whoops" << std::endl; }
};

using PMember = void (A::*)(int);

void hijack(A& s, int n, char dummy = 0);

template <PMember pf, typename T>
struct Hijack {
  friend void hijack(A& s, int n, T) {
    (s.*pf)(n);
  }
};

// explicit instantiate template instance.
template struct Hijack<&A::f, char>;

int main() {
  A a;
  hijack(a, 10);
  return 0;
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.