开发者

C++ templates: how to determine if a type is suitable for subclassing

Let's say I have some templated class depending on type T. T could be almost anything: int, int*, pair <int, int> or struct lol; it cannot be void, a reference or anything cv-qualified though. 开发者_C百科For some optimization I need to know if I can subclass T. So, I'd need some trait type is_subclassable, determined as a logical combination of basic traits or through some SFINAE tricks.

In the original example, int and int* are not subclassable, while pair <int, int> and struct lol are.

EDIT: As litb pointed out below, unions are also not subclassable and T can be a union type as well.

How do I write the trait type I need?


You want to determine whether it is a non-union class. There is no way known to me to do that (and boost hasn't found a way either). If you can live with union cases false positives, you can use a is_class.

template<typename> struct void_ { typedef void type; };

template<typename T, typename = void>
struct is_class { static bool const value = false; };

template<typename T>
struct is_class<T, typename void_<int T::*>::type> { 
  static bool const value = true; 
};

Boost has an is_union that uses compiler-specific builtins though, which will help you here. is_class (which boost also provides) combined with is_union will solve your problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜