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

前提是你 提交于 2019-12-29 07:32:10

问题


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. 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?


回答1:


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.



来源:https://stackoverflow.com/questions/6540948/c-templates-how-to-determine-if-a-type-is-suitable-for-subclassing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!