C ++模板:如何确定类型是否适合子类化 [英] C++ templates: how to determine if a type is suitable for subclassing

查看:140
本文介绍了C ++模板:如何确定类型是否适合子类化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一些模板类,取决于 T 类型。 T 几乎可以是任何东西: int int * pair< int,int> struct lol 它不能 void ,一个引用或任何cv限定。对于一些优化我需要知道,如果我可以子类 T 。所以,我需要一些特征类型 is_subclassable ,确定为基本特征的逻辑组合或通过一些SFINAE技巧。

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.

在原始示例中, int int * 不可子类化,而 pair < int,int> struct lol

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

:下面指出,联合也不是子类, T 也可以是联合类型。

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

如何写我需要的trait类型?

How do I write the trait type I need?

推荐答案

类。没有办法我知道这样做(和boost也没有找到一种方式)。如果你可以使用联合案例假阳性,你可以使用 is_class

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有一个 is_union ,它将使用编译器特定的内置,这将帮助您这里。 is_class (其中boost也提供)结合 is_union 将解决您的问题。

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.

这篇关于C ++模板:如何确定类型是否适合子类化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆