mrzacek mrzacek
mrzacek mrzacek

Reputation: 428

SFINAE - recursive template

I'm trying to do this:

struct A
{
    typedef void NoHalf;
};
struct B : A
{
    typedef A Half;
};
struct C : B
{
    typedef B Half;
};

template<class T, typename = T::NoHalf> void TEST() { };
template<class T, typename = T::Half> void TEST()
{
    TEST<T::Half>();
};

int main()
{
    TEST<A>();
    TEST<B>();
    TEST<C>();
};

So the TEST<C> function should do something with class C, then recurse TEST<B>, then to TEST<A> and stop there. Unfortunately I get bunch of errors like TEST has already been defined and funny enough also TEST identifier not found. What am I doing wrong and how to fix that?

Upvotes: 0

Views: 67

Answers (1)

mrzacek mrzacek
mrzacek mrzacek

Reputation: 428

Ok, so here's a solution, quite uglier, but seems working:

struct A
{
    typedef void Half;
    static const int I = 0;
};
struct B : A
{
    typedef A Half;
    static const int I = 1;
};
struct C : B
{
    typedef B Half;
    static const int I = 2;
};

template<class T> std::enable_if_t<std::is_void_v<T> > TEST() { };
template<class T> std::enable_if_t<!std::is_void_v<T> > TEST()
{
    printf("%i", T::I);
    TEST<T::Half>();
};


int main()
{
    TEST<A>();
    TEST<B>();
    TEST<C>();
};

Upvotes: 1

Related Questions