lundi 14 août 2017

template specialization for derived classes

I have a template class (that I cannot modify), let's call it SomeClass, that I'd like to specialize for classes that derive from a particular class only. Following this answer I was able to do this in gcc 6.3.1, but unfortunately I need to do it in gcc 4.9.2, and there it fails at compile time saying "partial specialization SomeClass<T> does not specialize any template arguments".

Is there any way I could change the below to make it work with gcc 4.9.2?

#include <iostream>
#include <string>

using namespace std;

struct A {
    string name() { return "A"; }
};

struct B : A {
    string name() { return "B"; }
};

struct C {
    string name() { return "C"; }
};

template<typename T, typename = std::enable_if_t<std::is_base_of<A, T>::value>>
using enable_if_a = T;

template<typename T>
struct SomeClass {
    using Type = T;
};

template<typename T>
struct SomeClass<enable_if_a<T>>
{
    using Type = A;
};

int main(int, char**)
{
    SomeClass<A>::Type el1;
    SomeClass<B>::Type el2;
    SomeClass<C>::Type el3;

    cout << el1.name() << "," << el2.name() << "," << el3.name() << endl;
}

Output:

A,A,C

Aucun commentaire:

Enregistrer un commentaire