如何从复制构造函数委托到通用复制构造函数模板
How delegate from copy constructor to universal copy constructor template?
如果我想编写一个通用复制构造函数(可以接受任何参数类型),这很容易做到:
class Widget {
public:
template<typename T> Widget(T&& other);
};
这不会阻止编译器生成传统的复制构造函数,所以我想自己编写并委托给模板。但我该怎么做呢?
class Widget {
public:
template<typename T> Widget(T&& other);
Widget(const Widget& other): ??? {} // how delegate to the template?
};
我试着这样写委托构造函数,
Widget(const Widget& other): Widget<const Widget&>(other){}
但是VC11, gcc 4.8和clang 3.2都拒绝它。
我怎么写我想写的委托复制构造函数?
不能为构造函数模板指定模板参数;你仅限于演绎。也许你可以从我以前的一个帖子中改编一个答案:
// NOT Tested!
#include <utility>
class Widget
{
enum fwd_t { fwd };
// Your true master constructor
template< typename T > Widget( fwd_t, T &&t );
public:
template < typename T >
Widget( T&& other );
: Widget( fwd, std::forward<T>(other) )
{}
Widget( const Widget& other )
: Widget( fwd, other )
{}
};
两个单参数构造函数转发给两个参数的兄弟构造函数
相关文章:
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 将重载的成员函数传递给函数模板
- C++17中函数模板中的静态数组初始化(MSVC 2019)
- 为什么 gcc 和 clang 为函数模板的实例化生成不同的符号名称?
- 为什么默认复制函数在按值发送参数时不调用?
- 具有常量引用参数的函数模板专用化
- std::span<const T> 作为函数模板中的参数
- 如何编写一个完美的缩写函数模板?
- 仅在函数模板中为那些定义了函数的类型执行函数
- 如何在C++中伪造虚拟可变参数函数模板?
- 以下代码中的函数模板有什么问题?
- 在 C++20 中是否不再允许在 std 中对程序定义类型的函数模板进行专用化?
- 在 c++ 中对字符串使用复制函数时打印的垃圾值
- 将显式实例化的函数模板与转换匹配
- 使用定义函数模板别名
- 函数模板返回类型
- C++有什么方法可以在既不调用函数模板也不提供其模板参数的情况下引用函数模板?
- 将构造函数复制为模板化的成员函数
- 启用基于类模板形参的构造函数时,是否总是需要复制该类模板形参?
- 如何从复制构造函数委托到通用复制构造函数模板