gpt4 book ai didi

c++ - 如何使用 Visual C++ 9 中的类型特征检测可按位移动的类型?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:34:02 25 4
gpt4 key购买 nike

我有一个类似 std::vector 的类,它是用 Visual C++ 2008 编译的。该类中有一 block 移动存储的元素 - 主体被重新分配或插入/部分删除完成。现在一些类型可以被 memmove()d 而其他类型需要在新位置复制构造,然后在原始位置销毁。

目前有一个实现“复制构造,然后销毁”的模板化函数,并且每种类型都有一个专门化,可以是 memmove()d。我想用 V isual C++ 2008 support of type traits以简化该任务。

我想要的是自动为每个 POD 选择 memmove()。我不介意使用该模板函数移动某些可以是 memmove() 的类型,但我不能容忍相反的情况 - 当一个数据类型不能是 memmove()d 是 memmove()d。

看起来 __is_pod() intrinsic 会做,但 MSDN 说它为内置类型返回 false。所以我想我还需要使用 __is_class() 来首先过滤掉非类。

所以我虽然以下会做:

if( !__is_class(T) ) { // not a struct and not a class - built-in type
//memmove()
} else if( __is_pod(T) ) { // is a struct or a class and is a POD
//memmove()
} else { // is a struct or a class and is not a POD
//DefaultMoveViaCopy()
}

我的解决方案行得通吗?

最佳答案

使用 boost 的 enable_if:

template <typename T, class Enabler = void>
struct SmartCopy
{
static void apply(const T& obj, T* dest)
{
// Generic copy...
}
}

template <typename T>
struct SmartCopy<T, typename boost::enable_if_c<__is_pod(T) || !__is_class(T)>::type >
{
static void apply(const T& obj, T* dest)
{
// memmove version...
}
}

template <typename T>
void smart_move(const T& obj, T* dest)
{
SmartCopy<T>::apply(obj, dest);
}

关于c++ - 如何使用 Visual C++ 9 中的类型特征检测可按位移动的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8069178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com