首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >创建is_primitive或is_inheritable模板

创建is_primitive或is_inheritable模板
EN

Stack Overflow用户
提问于 2013-03-21 00:56:27
回答 3查看 370关注 0票数 1

我想要创建一个模板来检查一个类类型是否是一个原语(int、char、float *等等)。这样做的原因是防止另一个模板试图扩展原语并导致编译时错误。到目前为止,我有一些关于以下内容的内容:

代码语言:javascript
复制
#include <typeinfo>
template<typename T>
struct is_primitive{
   const static bool value=std::is_fundamental<T>::value;
};

显然,这只是现在转发来自is_fundamental的结果。我想加上remove_pointer,remove_reference,等等.删除输入类的所有额外修饰符。,为了使T尽可能光秃秃,所有的清除都需要什么?

另一种办法是,下列解决办法同样悬而未决:

代码语言:javascript
复制
template<typename T>
struct is_inheritable{
   const static bool value=???;
};

但我很确定不可继承类的集合等于原始类的集合。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-03-22 00:12:20

我觉得你想要std::is_class<T>。只能从类类型继承。这是一个描述C++11类型分类特征的图表:在这里http://howardhinnant.github.io/TypeHiearchy.pdf

http://howardhinnant.github.io/TypeHiearchy.pdf

票数 5
EN

Stack Overflow用户

发布于 2013-03-21 07:56:43

我建议您集中精力检测在您的情况下需要继承的类型的属性,而不是考虑检测那些不需要继承的类型。幸运的是,您的类需要来自基类的其他属性,这些属性可以检查,因为派生类至少需要调用基类的一个构造函数。

尝试使用is_constructible或一些相关的类型特征:

代码语言:javascript
复制
// check that T::T(std::string,int); exists:
std::is_constructible< T, std::string, int >::value

// or these direct traits for the usual suspects...
std::is_default_constructible< T >::value
std::is_copy_constructible< T >::value
std::is_move_constructible< T >::value

对于您的另一个问题,如果在上述问题之后仍然相关,请查看std::decay,并将其与其他特性结合起来,以便在需要时去掉该类型:

代码语言:javascript
复制
template< typename T, typename = void >
struct strip
{
     typedef T type;
};

template< typename T >
struct strip< T, typename std::enable_if<
  !std::is_same< typename std::decay< T >::type, T >::value
>::type >
    : strip< typename std::decay< T >::type >
{
};

template< typename T >
struct strip< T, typename std::enable_if<
  std::rank< T >::value != 0
>::type >
    : strip< typename std::remove_all_extents< T >::type >
{
};

template< typename T >
struct strip< T, typename std::enable_if< std::is_pointer< T >::value >::type >
    : strip< typename std::remove_pointer< T >::type >
{
};

typedef const int*(&Test)[42];
static_assert( std::is_same< typename strip< Test >::type, int >::value, "" );

但是你需要弄清楚在你的情况下什么才是合适的。

票数 1
EN

Stack Overflow用户

发布于 2013-03-21 01:41:05

代码语言:javascript
复制
template <typename T>
struct remove_all { typedef typename std::remove_cv<T>::type type; };
template <typename T>
struct remove_all<T*> { typedef typename remove_all<T>::type type; };
template <typename T>
struct remove_all<T&> { typedef typename remove_all<T>::type type; };
template <typename T>
struct remove_all<T&&> { typedef typename remove_all<T>::type type; };

template<typename T>
struct is_primitive{
    typedef typename remove_all<T>::type TF;
    const static bool value=std::is_fundamental<TF>::value;
};

remove_all结构化讨论发现了这里

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15537604

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档