不可复制类型的嵌套列表初始化不起作用

问题描述

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,{}});

https://wandbox.org/permlink/EuYSJ2n2WTg368YS

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...