The reason it didn't work is because you specialized it for pair, not your class that inherits from pair (BTW generally a bad idea to inherit from stdlib classes). You could specialize it for D
.
template<class T>
struct A {
A(){cout << "not special\n";}
};
template<class T1, class T2>
struct A<pair<T1, T2>> {
A(){cout << "special\n";}
};
struct D : public pair<int, char>
{};
template<>
struct A<D> {
A(){cout << "special D\n";}
};
int main() {
A<D> a;
return 0;
}
Outputs special D
You can also use std::is_base_of
but it's gonna be a pain and I recommend against it. If your deadset on doing it you can have another class like this
template <typename T, bool B>
struct helper;
template <typename T>
struct helper<T,true>;
template <typename T>
struct helper<T,true>;
Then you can create that class inside the first one like
template<class T>
struct A {
helper<T,is_base_of<pair<int,char>,T>::value> h;
};
That should get you started I'll let you figure out the rest :).
Here's a more concise version with only one class.
template<class T,bool B = is_base_of<pair<int,char>,T>::value>
struct A;
template<class T>
struct A<T,true> {
A(){cout << "special\n";}
};
struct D : public pair<int, char>
{};
template<class T>
struct A<T,false> {
A(){cout << "not special\n";}
};
int main() {
A<D> a;
A<int> b;
return 0;
}