问题描述
void foo(std::pair<int,std::vector<std::unique_ptr<int>>>&&) {}
foo({{},{}});
上面没有编译错误消息,报告它试图调用 std::vector<std::unique_ptr<int>>
的复制构造函数(已删除)。但是,以下工作
void foo(std::vector<std::unique_ptr<int>>&&) {}
void foo(const std::vector<std::unique_ptr<int>>&) {}
foo({});
我缺少哪些规则使第二个示例有效而第一个示例无效?
示例:https://wandbox.org/permlink/wE913kQTulV94uDf
解决方法
似乎我对自己的问题有了答案——这不起作用,因为嵌套列表初始化重载只有以下 std::pair
constructor 匹配
pair( const T1& x,const T2& y );
另一个带有两个参数的 std::pair
constructor 是模板化的,没有默认类型,所以没有考虑
template< class U1,class U2 >
pair( U1&& x,U2&& y );
如果我们要将其更改为第二个构造函数具有默认类型或具有非模板化右值重载的类型,则上述方法有效
template <typename T1,typename T2>
class Pair {
public:
Pair(const T1&,const T2&) {}
Pair(T1&&,T2&&) {}
};
void foo(Pair<int,std::vector<std::unique_ptr<int>>>&&) {}
foo({{},{}});
https://wandbox.org/permlink/pbmme350X7XjM8cI
或
template <typename T1,const T2&) {}
template <typename U1 = T1,typename U2 = T2>
Pair(U1&&,U2&&) {}
};
void foo(Pair<int,{}});