我收到这个错误:
C:\Program Files(x86(\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\include\xmemory0:881:error:C2661:'sstd::array<uint,3>:array’:没有重载函数接受3个参数
在这一行代码:
template<class _Objty,
class... _Types>
static void construct(_Alloc&, _Objty * const _Ptr, _Types&&... _Args)
{ // construct _Objty(_Types...) at _Ptr
::new (const_cast<void *>(static_cast<const volatile void *>(_Ptr)))
_Objty(_STD forward<_Types>(_Args)...); // ** Error is here
}
我是这样使用std::array<uint, 3>
的:
void MyClass::myMethod(
// ...
, std::vector<std::array<uint, 3>> &indices
// ...
, const size_t ssteps
// ...
)
{
// ...
indices.reserve(2*ssteps);
auto steps = int(ssteps);
auto offs = steps;
auto last = steps - 1;
// ...
indices.emplace_back(0, last, offs);
indices.emplace_back(last, offs + last, offs);
// ...
}
我不明白为什么xmemory0
包含的文件中会出现此错误。任何提示都将不胜感激。
正如@kakkoko已经指出的:
indices.emplace_back(0, last, offs)
调用构造函数array<uint, 3>::array(0, last, offs)
,但数组没有这样的构造函数;
不幸的是,一对额外的花括号是不够的:
indices.emplace_back({ 0u, last, offs }); // Doesn't work! :-(
输出:
main.cpp: In function 'int main()':
main.cpp:11:42: error: no matching function for call to 'std::vector<std::array<unsigned int, 3> >::emplace_back(<brace-enclosed initializer list>)'
11 | indices.emplace_back({ 0u, last, offs });
| ^
In file included from /usr/local/include/c++/10.2.0/vector:72,
from main.cpp:2:
/usr/local/include/c++/10.2.0/bits/vector.tcc:109:7: note: candidate: 'std::vector<_Tp, _Alloc>::reference std::vector<_Tp, _Alloc>::emplace_back(_Args&& ...) [with _Args = {}; _Tp = std::array<unsigned int, 3>; _Alloc = std::allocator<std::array<unsigned int, 3> >; std::vector<_Tp, _Alloc>::reference = std::array<unsigned int, 3>&]'
109 | vector<_Tp, _Alloc>::
| ^~~~~~~~~~~~~~~~~~~
/usr/local/include/c++/10.2.0/bits/vector.tcc:109:7: note: candidate expects 0 arguments, 1 provided
coliru上的实时演示
因此,这些元素必须明确构建:
indices.emplace_back(std::array<uint, 3>{ 0u, last, offs }); // Does work. :-)
coliru上的实时演示
或者必须使用std::vector::push_back()
:
indices.push_back(std::array<uint, 3>{ 0u, last, offs });
coliru上的实时演示
完整的演示:
#include <array>
#include <iostream>
#include <vector>
using uint = unsigned;
int main()
{
std::vector<std::array<uint, 3>> indices;
const uint last = 3, offs = 4;
indices.emplace_back(std::array<uint, 3>{ 0u, last, offs });
indices.push_back({ last, offs + last, offs });
std::cout << "indices: {";
const char *sep = "n";
for (const std::array<uint, 3> &indicesI : indices) {
std::cout << sep << " {";
const char *sepI = " ";
for (const uint i : indicesI) {
std::cout << sepI << i;
sepI = ", ";
}
std::cout << " }";
sep = ",n";
}
std::cout << "n}n";
}
输出:
indices: {
{ 0, 3, 4 },
{ 3, 7, 4 }
}
coliru上的实时演示