可移动类型的类型特征? [英] Type trait for moveable types?

查看:69
本文介绍了可移动类型的类型特征?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个模板,如果T具有move构造函数,则该模板将表现为一种方式,如果T没有其构造,则其行为将呈现另一种方式。我试图寻找一种可以识别出这种特征的类型特征,但是没有运气,为此我尝试写出自己的类型特征的尝试失败了。

I'm trying to write a template that behaves one way if T has a move constructor, and another way if T does not. I tried to look for a type trait that could identify this but have had no such luck and my attempts at writing my own type trait for this have failed.

任何帮助表示感谢。

推荐答案

我觉得有必要指出一个细微的区别。

I feel the need to point out a subtle distinction.

虽然< type_traits> 确实提供了 std :: is_move_constructible std :: is_move_assignable ,它们不能完全检测类型是否具有移动构造函数(分别是移动赋值运算符)。例如, std :: is_move_constructible< int> :: value true ,并考虑以下情况:

While <type_traits> does provide std::is_move_constructible and std::is_move_assignable, those do not exactly detect whether a type has a move constructor (resp. move assignment operator) or not. For instance, std::is_move_constructible<int>::value is true, and consider as well the following case:

struct copy_only {
    copy_only(copy_only const&) {} // note: not defaulted on first declaration
};
static_assert( std::is_move_constructible<copy_only>::value
             , "This won't trip" );

请注意,用户声明的副本构造函数取消了move构造函数的隐式声明:甚至没有隐藏的,编译器生成的 copy_only(copy_only&&)

Note that the user-declared copy constructor suppresses the implicit declaration of the move constructor: there is not even a hidden, compiler-generated copy_only(copy_only&&).

类型特征的目的是为了方便通用编程,因此根据表达式指定(出于概念考虑)。 std :: is_move_constructible< T> :: value 在问一个问题:例如 T t = T {}; 有效吗?它不是在问(假设 T 是这里的类类型)是否有 T(T&&) (或任何其他有效形式)声明了声明的构造方法。

The purpose of type traits is to facilitate generic programming, and are thus specified in terms of expressions (for want of concepts). std::is_move_constructible<T>::value is asking the question: is e.g. T t = T{}; valid? It is not asking (assuming T is a class type here) whether there is a T(T&&) (or any other valid form) move constructor declared.

我不知道您要做什么,而且我没有理由不相信 std :: is_move_constructible 不适合您的目的。

I don't know what you're trying to do and I have no reason not to believe that std::is_move_constructible isn't suitable for your purposes however.

这篇关于可移动类型的类型特征?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆