Specializing C++ template based on presence/absense of a class member?

c++, template-specialization, templates, type-traits

Solution

Another (C++03) approach:

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
};

Problem

Consider the following: ``` struct A { typedef int foo; }; struct B {}; template<class T, bool has_foo = /* ??? */> struct C {}; ``` I want to specialize C so that C<A> gets one specialization and C<B> gets the other, based on the presence or absence of typename T::foo. Is this possible using type traits or some other template magic? The problem is that everything I've tried produces a compile error when instantiating C<B> because B::foo doesn't exist. But that's what I want to test! Edit: I think ildjarn's answer is better, but I finally came up with the following C++11 solution. Man is it hacky, but at least it's short. :) ``` 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)> ```

Original source