std :: swap无法使用std :: array

时间:2016-06-03 15:39:56

标签: c++ arrays

我有一些代码要求我将一些数据放入std::array。我想我可以通过交换两个阵列并丢弃其中一个来做到这一点。这是代码

int main()
{
    std::array<double, 10> a;
    std::array<double, 5> b;
    /*populate b*/
    /*swap them round*/
    std::swap(a, b);
}

但是我得到了一个非常奇怪的编译器错误(MSVC2013)。

CashFlows.cpp(27): error C2665: 'std::swap' : none of the 3 overloads could convert all the argument types
include\exception(502): could be 'void std::swap(std::exception_ptr &,std::exception_ptr &)'
include\tuple(572): or 'void std::swap(std::tuple<> &,std::tuple<> &)'
include\thread(232): or 'void std::swap(std::thread &,std::thread &) throw()'
while trying to match the argument list '(std::array<_Ty,_Size>, std::array<_Ty,_Size>)'
with
[
  _Ty=double,
  _Size=0x0a
]
and
[
  _Ty=double,
  _Size=0x05
]

我不明白。 std::tuple<>等与此有什么关系?

2 个答案:

答案 0 :(得分:7)

对象ab 从根本上不同的类型,因为它们是不同的模板实例。

因此,您不能在std::swap中一起使用它们,因为参数必须是相同的类型。

你的编译器找不到合适的重载(被授予,它显示的那些看起来很奇怪),所以发出你看到的错误。

答案 1 :(得分:1)

  

我不明白。 std::tuple<>等与此有什么关系?

您只需在提示上进一步阅读错误消息。编译器只列出可能合适的可用构造函数声明:

  

可以

void std::swap(std::exception_ptr &,std::exception_ptr &)
     

void std::swap(std::tuple<> &,std::tuple<> &)
     

void std::swap(std::thread &,std::thread &) throw()

您也可以看到这些documented here