- 936 名前:はちみつ餃子 mailto:sage [2017/11/21(火) 00:48:45.97 ID:KkY90WH60.net]
- >>913
昨日 >>885 でまわりくどいメタプログラミングと言ってたのがそれだ。 State パターンのように特定のメンバ関数を持っていることを強制したいときには それを判定するトレイツを作って対応する。 たとえば >>886 にあるコードを対象に考えて、 「あるクラスがそのクラス自身のポインタを返す next という名前のメンバ関数を持っているか」 を判定するトレイツはこうなる。 template<class T> class has_next { template<class U, class V = T> struct helper : std::false_type {}; template<class U> struct helper<U, typename std::enable_if<std::is_same<decltype(std::declval<U>().next()), U*>::value, T>::type> : std::true_type {}; public: static const bool value = helper<T>::value; }; C++ 標準の type_traits を真似してるので使い方もだいたい同じ。 static_assert(!has_next<TShelfIterator<Book>>::value, "TShelfIterator must has next() method."); みたいに書いておけば TShelfIterator<Book> がメンバ関数 next を持っていることが保証される。 持っていなければコンパイル時にエラーになるから。 ここではひとつのメンバ関数を判定するだけのものを作ったけど、 Boost にはもっと汎用的にいい感じにかけるやつが有った気がする。 知らんけど。
|

|