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

How do I detect bitwise-moveable types using type traits in Visual C++ 9?

本文关键字:类型 特征检测 移动 Visual c++      更新时间:2023-10-16

我有一个用Visual c++ 2008编译的std::vector类。在这个类中有一个部分是移动存储元素的——要么重新分配主体,要么进行插入/部分擦除。现在,有些类型可以直接使用memmove() d,而其他类型则需要在新位置复制构造,然后在原始位置销毁。

目前有一个模板化函数,实现了"复制构造,然后销毁",并且每种类型都可以是memmove() d。我想使用Visual c++ 2008支持类型特征来简化该任务。

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

看起来像__is_pod()固有的,但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);
}