News for hackers. Stuff that matters.
Re:A Crash Course on ML Modules (2015) by zvrba on Wednesday February 28, 2018 @01:38AM (#16481148)
So, in C++

  class M
  {
    // This is private
    std::vector<int> _sorted;
  public:
    // This is your "import"
    M(const std::vector<int>& v) : _sorted(v) {
      std::sort(_sorted.begin(), _sorted.end());
    }
    // Add other ADT operations that preserve the invariant
  }

A more indirect way that more closely mimics the ML thing:

  struct M
  {
    // Everything private; but as M is "friend" it can access all members
    class Sorted {
      friend M;
      std::vector<int> value;
    }

    static Sorted import(std::vector<int> v) {
      std::sort(v.begin(), v.end());
      return Sorted{v};
    }
  }
Usage:

  auto s = M::import(std::vector<int>{4, 3, 2, 1});
  ++s.value[0]; // ERROR: value is private
Yes, you can use casts to access the private members. As others have pointed out, unsafe operations exist in Ocaml/Haskell/... too.

There are no comments on this comment yet.