【发布时间】:2011-10-02 05:03:40
【问题描述】:
在 C++0x 中,我想确定一个类是否微不足道/是否具有标准布局,以便我可以使用 memcpy()、memset() 等...
我应该如何使用 type_traits 实现下面的代码,以便我可以确认一个类型是微不足道的?
template< typename T >
bool isTrivialType()
{
bool isTrivial = ???
return isTrivial;
}
注意:is_pod() 限制性太强:我希望我的班级有简单的构造函数等... ...为方便起见。
补充:我认为 std::is_standard_layout 可能会给我我正在寻找的东西。 1.如果我添加构造函数,它仍然返回true 2.如果我添加一个虚方法,它返回false 这是我需要确定是否可以使用memcpy()、memset()
编辑:来自 Luc Danton 的解释和下面的链接(澄清):
struct N { // neither trivial nor standard-layout
int i;
int j;
virtual ~N();
};
struct T { // trivial but not standard-layout
int i;
private:
int j;
};
struct SL { // standard-layout but not trivial
int i;
int j;
~SL();
};
struct POD { // both trivial and standard-layout
int i;
int j;
};
让 memcpy() 开心:
// N -> false
// T -> true
// SL -> ??? (if there are pointer members in destructor, we are in trouble)
// POD -> true
所以看起来 is_trivial_class 是正确的:is_standard_layout 不一定是正确的......
【问题讨论】:
-
它看起来像新添加的 std::is_standard_layout 可以做我想做的 - 不像 POD,我可以添加构造函数,它仍然会返回 true
-
标准版面不太对;例如,
std::vector可能是标准布局,但使用memcpy将是一个坏主意。
标签: c++ c++11 typetraits