4 ms·
So, in C++ class M { // This is private std::vector<int> _sorted; public: // This is your "import" M(const std::vector<int>& v) : _sorted
by zvrba 9y ago
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.