C++ templates: how to determine if a type is suita

2019-01-26 06:16发布

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条回答
Fickle 薄情
2楼-- · 2019-01-26 07:00

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.

查看更多
登录 后发表回答