4000-520-616
欢迎来到免疫在线!(蚂蚁淘生物旗下平台)  请登录 |  免费注册 |  询价篮
主营:原厂直采,平行进口,授权代理(蚂蚁淘为您服务)
咨询热线电话
4000-520-616
当前位置: 首页 > 新闻动态 >
新闻详情
...trivially_destructible”。 - IT屋-程序员软件开发技术分享社区
来自 : www.it1352.com/4975...html 发布时间:2021-03-25

在C ++ 11标准的细化过程中,似乎 is_trivially_destructible 被视为比更好/更一致的名称has_trivial_destructor 。



这是一个相对较新的开发,因为我的g ++ 4.7.1仍然使用旧的名称,它被固定为符合标准自4.8起:



http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52702



我一直懒地使用 #if 这有利于我的编译器:



 #if TRIVIAL_DESTRUCTOR_TYPE_TRAIT_MATCHES_STANDARD 
template class T
using is_trivially_destructible = std :: is_trivially_destructible T
#else
template class T
using is_trivially_destructible = std :: has_trivial_destructor T
#endif


...但现在我试图与4.8用户和其他编译器追逐标准。




解决方案

/ div>

这适用于我与GCC 4.7和4.8,正确地告诉我是否提供旧的或新的trait:



 #include type_traits 

namespace std
{
template typename struct has_trivial_destructor;
template typename struct is_trivially_destructible;
}

template typename T
class has_cxx11_trait_helper
{
template typename T2,bool = std :: is_trivially_destructible T2 :: type :: value
static std :: true_type test(int);

template typename T2,bool = std :: has_trivial_destructor T2 :: type :: value
static std :: false_type test(...);

public:
typedef decltype(test T (0))type;
};

template typename T
struct have_cxx11_trait:have_cxx11_trait_helper T :: type
{};

int main()
{
static_assert(have_cxx11_trait int :: value,\"new trait\");
}


N.B。我声明(但不定义)两个traits,因为标准库(可能)不会声明两者,如果名称甚至没有声明,那么你不能引用 std :: is_trivially_destructible 。所以我声明它们,但只有由库定义的一个将可用。添加声明到命名空间 std 是技术上未定义的行为,所以使用它自己的风险(在这种情况下不可能擦拭你的硬盘驱动器。)

$不幸的是,不提供新trait的旧编译器可能无法处理代码 - 我没有检查它是否与GCC 4.6一起使用



现在您可以定义自己的便携式特性:



 template typename T& 
使用is_trivially_destructible
= typename std :: conditional have_cxx11_trait T :: value,
std :: is_trivially_destructible T ,
std :: has_trivial_destructor T ::类型;


has_trivial_destructor 的语义不是与新特性相同,但对于不支持新特性的旧编译器,这是一个合理的近似。



或者,您可以使用static polymoprhism来获取不同的代码,具体取决于可用的类型特征。通过专门化模板或通过重载和标签分派,如下:



 template typename T 
void foo_helper(const T std :: true_type)
{
//使用std :: is_trivially_destructible的代码
}

template T>
void foo_helper(const T std :: false_type)
{
//不同的代码使用std :: has_trivial_destructor
}

template typename T>
void foo(const T t)
{
//做常用的东西

//取决于trait的东西
foo_helper(t,has_cxx11_trait T> {});

//更常见的资料
}


在回答这个问题时受到了损害。


本文地址:IT屋 编写代码,当“has_trivial_destructor”而不是“is_trivially_destructible”。

本文链接: http://ndestructible.immuno-online.com/view-748708.html

发布于 : 2021-03-25 阅读(0)