";结果类型必须是可从输入范围的值类型""构造的;创建std::vector时

"result type must be constructible from value type of input range" when creating a std::vector

本文关键字:quot 类型 创建 std vector 输入 结果 范围      更新时间:2023-10-16

我有一个类成员,看起来像这个

class Controller {
protected:
// other stuff
std::vector<Task<event_t, stackDepth>> taskHandlers; 
//some more stuf
}

Task类是non-defaultConstructable、non-copyConstructable和non-copyAssignable,但却是moveConstructable和moveAssignable。我能读到的所有内容(尤其是std::vector文档(都让我认为应该编译它,但错误列表如下(此处为完整输出(:

/usr/include/c++/9/bits/stl_uninitialized.h:127:72: error: static assertion failed: result type must be constructible from value type of input range
127 |       static_assert(is_constructible<_ValueType2, decltype(*__first)>::value,
|                                                                        ^~~~~

Task设置为defaultConstructable没有帮助。错误指向类别Controller的定义。我在c++17模式下使用GCC 9.3.0。我做错什么了吗?

根据当前信息,我的最佳猜测是,您以某种方式弄乱了移动构造函数语法——仅使用emplace_back:的工作示例

下面编译得很好,链接到godbolt:

#include <vector>
class X
{
public:
X(int i) : i_(i){}
X() = delete;
X(const X&) = delete;
X(X&&) = default;//change this to 'delete' will give a similar compiler error
private:
int i_;
};

int main() { 
std::vector<X> x;
x.emplace_back(5);
}

再现错误result type must be constructible from value type of input range

导螺杆

#include <vector>
#include <string>
#include <iostream>
int main() {
typedef std::vector<std::string> StrVec;
StrVec s1("a", "b"); // error
// stl_uninitialized.h:127:7: error: static_assert failed due to requirement 'is_constructible<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, const char &>::value' "result type must be constructible from value type of input range"
//StrVec s2("a", "b", "c"); // error
// error: no matching constructor for initialization of 'StrVec' (aka 'vector<basic_string<char> >')
StrVec s3({"a", "b"}); // ok
StrVec s4({"a", "b", "c"}); // ok
typedef std::vector<int> IntVec;
IntVec i1(1, 2); // silent error
for (auto i : i1) {
std::cout << "i = " << i << 'n';
}
// silent error:
// output:
// i = 2
// expected:
// i = 1
// i = 2
//IntVec i2(1, 2, 3); // error
// error: no matching constructor for initialization of 'IntVec' (aka 'vector<int>')
IntVec i3({1, 2}); // ok
IntVec i4({1, 2, 3}); // ok
}