mardi 23 janvier 2018

Function Template Specialization Syntax aggregating templated types

With respect to function template specialization, I would like help with a bit of syntax. The following is a simplified scenario:

Base header:

template <typename T>
void Foo(T* t) { TRACE("Default Foo impl"); }  // <-- default implementation

template <typename T>
struct Base
{
    explicit Base()
    {
        static_assert(std::is_base_of<Base, T>::value, "T must derive from Base");
        Foo(static_cast<T*>(this));
    }
};

Derived_X header:

struct Derived_X : public Base<Derived_X>
{
    explicit Derived_X() : Base<Derived_X> { } { }
};

// no specialization will be implemented --> using default

Derived_Y header:

struct Derived_Y : public Base<Derived_Y>
{
    explicit Derived_Y() : Base<Derived_Y> { } { }
};

template <>  // Foo specialization for Derived_Y
void Foo<Derived_Y>(Derived_Y* t)
{
    Foo(static_cast<Base<Derived_Y>*>(t));  // <-- call default impl
    TRACE("Derived_Y Foo impl");
}

Derived_Z header:

template <typename T>
struct Derived_Z : public Base<T>
{
    explicit Derived_Z() : Base<T> { }
    {
        static_assert(std::is_base_of<Derived_Z, T>::value, "T must derive from Derived_Z");
    }
};

/*  What does this specialization look like?
template <typename T>
void Foo<Derived_Z<T>>(Derived_Z<T>* t)
{
    Foo(static_cast<Base<T>*>(t));  // <-- call default impl
    TRACE("Derived_Z<T> Foo impl");
}
// */

MostDerived Header:

struct MostDerived : public Derived_Z<MostDerived>
{
    explicit MostDerived() : Derived_Z<MostDerived> { } { }
};

template <>
void Foo<MostDerived>(MostDerived* t)
{
    Foo(static_cast<Derived_Z<MostDerived>*>(t));  // <-- call Derived_Z impl
    TRACE("MostDerived Foo impl");
}

Usage:

int main()
{
    Derived_X dx { };   // <-- "Default Foo impl"
    Derived_Y dy { };   // <-- "Default Foo impl" && "Derived_Y Foo impl"
    MostDerived md { }; // <-- "Default Foo impl" && "MostDerived Foo impl"
}

I have not been able to determine how to specialize Foo for Derived_Z. Any help would be most appreciated!

Aucun commentaire:

Enregistrer un commentaire