8

考虑以下:

struct A {
  typedef int foo;
};

struct B {};

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

我想根据类型名 T::foo 的存在与否来特化 C,以便 C<A> 获得一种特化,而 C<B> 获得另一种特化。这可能使用类型特征或其他一些模板魔法吗?

问题是我在实例化 C<B> 时尝试的所有操作都会产生编译错误,因为 B::foo 不存在。但这就是我想要测试的!


编辑:我认为 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 回答