1

Declaring a member private means there should never be a legal way to access it directly from outside. But template explicit instantiation breaks the law. What's the consideration of this? Or it's a defect?

Example:

#include <cassert>
#include <iostream>

class A {
 public:
  int X() { return x_; }

 private:
  int x_;
};

int A::*FiledPtr();
template <int A::*M>
struct Rob {
  friend int A::*FiledPtr() { return M; }
};
template struct Rob<&A::x_>;

int main() {
  A o;
  o.*FiledPtr() = 10;
  assert(o.X() == 10);
}
Andy
  • 4,783
  • 2
  • 26
  • 51
zclll
  • 77
  • 7
  • 2
    *"Declaring a member private means there should never be a legal way to access it directly from outside"* - There is no such extreme "safety" in any language. Even Java allows reflection to access private members (unless you cripple your app performance-wise). – StoryTeller - Unslander Monica Oct 11 '22 at 14:20
  • 1
    Related: https://stackoverflow.com/q/39807325, https://stackoverflow.com/q/23920027 – Artyer Oct 11 '22 at 14:20
  • 2
    Are you asking if the C++ committee has recognized this to be a language defect? Or are you asking if it _feels_ like a defect? – Drew Dormann Oct 11 '22 at 14:26
  • The thing with C++ is it gives you a lot of control, almost anything is possible even if you want to break stuff. C++ is not going to babysit you. And IMO the construct shown shouldn't make it past any serious code review. – Pepijn Kramer Oct 11 '22 at 14:52
  • @DrewDormann Surely there are many methods that make us able to break the access control which is UB. But the way I mentioned above is not. So there must be some consideration by the committee because is easy to prohibit it by checking the access permission before the explicit instantiation. Why they didn't? What's the consideration? – zclll Oct 12 '22 at 05:40

0 Answers0