c++类同居的copy(reference)构造函数和move构造函数 [英] c++ copy (reference) constructor and move constructor of class cohabitation
本文介绍了c++类同居的copy(reference)构造函数和move构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此处显示意图的代码:
template<typename T>
class B
{
public:
// this should indeed set t_ as a reference to t
B(T& t):t_(t){}
// this should instead set t_ as a copy of t
B(T&& t):t_(t){}
T& t_; // maybe type should be something else ?
};
A a;
B b1(a); // fine
B b2(A()); // problem
有可能吗?
推荐答案
在 C++17 中,使用 类模板参数推导(CTAD),你可能会这样做:
In C++17, with Class Template Argument Deduction (CTAD), you might do:
template<typename T>
class B
{
public:
B(T&& t):t_(t){}
T t_;
};
template <typename T> B(T&) -> B<T&>;
template <typename T> B(T&&) -> B<T>;
这篇关于c++类同居的copy(reference)构造函数和move构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文