【问题标题】:How do I detect bitwise-moveable types using type traits in Visual C++ 9?如何使用 Visual C++ 9 中的类型特征检测按位可移动的类型?
【发布时间】:2011-11-09 17:42:07
【问题描述】:

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

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

我想要的是自动选择每个 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()
}

我的解决方案行得通吗?

【问题讨论】:

标签: c++ visual-c++ types typetraits


【解决方案1】:

使用 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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 2016-09-13
    • 1970-01-01
    • 1970-01-01
    • 2015-09-19
    • 1970-01-01
    • 2010-12-03
    相关资源
    最近更新 更多