はいあります。
私はしばらくの間この方法を提唱しようとしてきましたが、基本的な考え方はKey
クラスを使用することです。
これによって の使用が実際になくなるfriend
わけではありませんが、公開されている一連の実装の詳細が削減されます。
class set;
// 1. Define the Key class
class set_key: noncopyable { friend class set; set_key() {} ~set_key() {} };
class set
{
// 2. Define the iterator
class iterator
{
public:
void public_method();
void restricted_method(set_key&);
}; // class iterator
}; // class set
現在restricted_method
は公開されているため、set
への特別なアクセスは必要ありませんiterator
。ただし、その使用はインスタンスを渡すことができる人に制限されていset_key
ます...そして便利なことにset
、そのようなオブジェクトを構築することしかできません。
Note that set
may actually pass a set_key
object to someone else it trusts. It is a key in the traditional sense: if you give a key of your flat to someone, it may entrust it to another person. However because of the semantics of the key class (non copyable, only set
may construct and destroy it) this is normally limited to the duration of the scope of the key
object.
Note that a evil hack is always possible, namely *((set_key*)0)
. This scheme protects from Murphy, not Machiavelli (it's impossible in C++ anyway).