8

次の点を考慮してください。

struct A {
  typedef int foo;
};

struct B {};

template<class T, bool has_foo = /* ??? */>
struct C {};

typename T::foo の有無に基づいて、C<A> が 1 つの特殊化を取得し、C<B> が別の特殊化を取得するように、C を特殊化したいと考えています。これは、型特性またはその他のテンプレート マジックを使用して可能ですか?

問題は、 B::foo が存在しないため、 C<B> をインスタンス化するときに、私が試したすべての方法でコンパイル エラーが発生することです。しかし、それは私がテストしたいものです!


編集:ildjarnの答えの方が良いと思いますが、最終的に次のC++ 11ソリューションを思いつきました。男はハッキーですが、少なくとも短いです。:)

template<class T>
constexpr typename T::foo* has_foo(T*) {
  return (typename T::foo*) 1;
}
constexpr bool has_foo(...) {
  return false;
}
template<class T, bool has_foo = (bool) has_foo((T*)0)>
4

2 に答える 2

6

別の (C++03) アプローチ:

template<typename T>
struct has_foo
{
private:
    typedef char no;
    struct yes { no m[2]; };

    static T* make();
    template<typename U>
    static yes check(U*, typename U::foo* = 0);
    static no check(...);

public:
    static bool const value = sizeof(check(make())) == sizeof(yes);
};

struct A
{
    typedef int foo;
};

struct B { };

template<typename T, bool HasFooB = has_foo<T>::value>
struct C
{
    // T has foo
};

template<typename T>
struct C<T, false>
{
    // T has no foo
};
于 2012-04-27T17:05:22.337 に答える
2

次のようなものが役立つかもしれません: has_member

typedef char (&no_tag)[1]; 
typedef char (&yes_tag)[2];

template< typename T > no_tag has_member_foo_helper(...);

template< typename T > yes_tag has_member_foo_helper(int, void (T::*)() = &T::foo);

template< typename T > struct has_member_foo {
    BOOST_STATIC_CONSTANT(bool
        , value = sizeof(has_member_foo_helper<T>(0)) == sizeof(yes_tag)
        ); }; 

template<class T, bool has_foo = has_member_foo<T>::value> 
struct C {};
于 2012-04-27T16:58:23.197 に答える