【发布时间】:2019-10-29 20:10:15
【问题描述】:
我正在尝试返回一个std::tuple,其中包含一个不可复制构造类型的元素。这似乎阻止了我使用默认的类构造函数来构造元组。例如,要返回一个包含Foo 的元组,必须创建一个foo 实例和std::moved:
class Foo {
public:
Foo(const Foo&) = delete;
Foo(Foo&&) = default;
int x;
};
tuple<int, Foo> MakeFoo() {
Foo foo{37};
// return {42, {37}}; // error: could not convert ‘{42, {37}}’ from ‘’ to ‘std::tuple’
return {42, std::move(foo)};
}
另一方面,如果类被定义为具有复制构造函数,则元组的构造可以正常工作:
class Bar {
public:
Bar(const Bar&) = default;
int x;
};
tuple<int, Bar> MakeBar() {
return {42, {37}}; // compiles ok
}
有没有办法将MakeBar 语法与Foo 类一起使用?
【问题讨论】:
-
return {42, Foo{37}};呢? -
@super 这是一个改进,但我仍然想了解为什么编译器无法推断出这种用法。