Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ template specialization and derivation

Tags:

c++

templates

When using template like this:

class A {…}
class B : A {…}
class C : A {…}

template<typename T>
class D{…}

I need T can only be B or C. Which means T must be a derivation of A.

Is there any way to do this? Thanks!

like image 658
Jingcheng Yu Avatar asked Dec 19 '22 01:12

Jingcheng Yu


1 Answers

Use std::is_base_of along with std::enable_if:

template<typename T, typename X = std::enable_if<std::is_base_of<A, T>::value>::type>
class D{...}

Note that it will accept any T as long as it derives from A. If you need T to be either B or C, then you need to modify it, and use std::is_same or/and std::conditional along with std::enable_if.

You could make it clean as:

template<typename T, typename Unused = extends<T,A>>
class D{...}

where extends is defined as:

template<typename D, typename B>
using extends = typename std::enable_if<std::is_base_of<B,D>::value>::type;

static_assert can also be used (like other answers have shown) if you want it to result in error and compilation failure. However if you need selection or deselection, say from many specializations, then use the above approach.

Hope that helps.

like image 183
Nawaz Avatar answered Dec 22 '22 09:12

Nawaz