pts*_*pts 7 c++ move-constructor c++11
我想检测(并使用 中的结果std::enable_if)C++ 类是否定义了移动构造函数。
以下程序打印MOVE,因此使用std::is_move_constructible不是这样做的方法:
#include <stdio.h>
#include <type_traits>
class C {
public:
C() { puts("C()"); }
C(int) { puts("C(int)"); }
~C() { puts("~C()"); }
C(const C&) { puts("C(const C&)"); }
// C(C&&) { puts("C(C&&)"); }
C& operator=(const C&) { puts("C="); return *this; }
};
int main(int argc, char** argv) {
(void)argc; (void)argv;
if (std::is_move_constructible<C>::value) puts("MOVE");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我需要一个程序,MOVE只有当我取消注释包含&&.
简短的回答:这是不可能的。
更多细节,基于@TobySpeight 的评论:
如果该类不包含C(C&&) = delete;,则无法检测它是否包含C(C&&) { ... }:std::is_move_constructible<C>::value在任何一种情况下都为真,并且没有其他方法可以检测到它。
C(C&&) = delete;可以检测到的存在:如果存在,std::is_move_constructible<C>::value则为假C(C&&) = delete;。
在这个对“理解std::is_move_constructible”的回答中有更多解释。
为了避免在 中缓慢复制std::vector::push_back,不需要检测用户定义的移动构造函数。这是替代方案,基于@NirFriedman 的评论:
对于旧类,这将使用成员交换(快速)。对于新类,它将使用移动构造函数(快,也快一点)。对于小类,它将使用复制构造函数(假设对于小类足够快)或移动构造函数(如果可用)。
这是我快速std::vector::push_back检测成员交换的最终解决方案:https : //github.com/pts/fast_vector_append/blob/master/fast_vector_append.h
| 归档时间: |
|
| 查看次数: |
1936 次 |
| 最近记录: |