问题是您在返回之前将不可复制的ofstream 复制到元组中。
一种解决方案是在返回之前将 ofstreams 移动到元组中:
#include<string>
#include<tuple>
#include<fstream>
#include<iostream>
std::tuple<std::ofstream, std::ofstream, std::ofstream>
set_ofstream_tuple()
{
std::ofstream out1("out1.txt", std::ofstream::out);
out1 << "this is out1.txt" << std::endl;
std::ofstream out2("out2.txt", std::ofstream::out);
out2 << "this is out2.txt" << std::endl;
std::ofstream out3("out3.txt", std::ofstream::out);
out3 << "this is out3.txt" << std::endl;
return std::make_tuple(std::move(out1), std::move(out2), std::move(out3));
}
int main() {
std::ofstream out1, out2, out3;
std::tie(out1, out2, out3) = set_ofstream_tuple();
/// make use of there ofstreams more here
}
证明:on godbolt
另一种解决方案是在创建过程中使用元组作为主存储:
#include<string>
#include<tuple>
#include<fstream>
#include<iostream>
std::tuple<std::ofstream, std::ofstream, std::ofstream>
set_ofstream_tuple()
{
auto streams = std::make_tuple(std::ofstream("out1.txt", std::ofstream::out),
std::ofstream("out2.txt", std::ofstream::out),
std::ofstream("out3.txt", std::ofstream::out));
auto& out1 = std::get<0>(streams);
auto& out2 = std::get<1>(streams);
auto& out3 = std::get<2>(streams);
out1 << "this is out1.txt" << std::endl;
out2 << "this is out2.txt" << std::endl;
out3 << "this is out3.txt" << std::endl;
return streams;
}
int main() {
std::ofstream out1, out2, out3;
std::tie(out1, out2, out3) = set_ofstream_tuple();
/// make use of there ofstreams more here
}
从 c++17 开始,我们将能够使用即将推出的 std::optional 避免空的 ofstreams 的冗余构造(此处使用 std::experimental 进行演示):
#include<string>
#include<tuple>
#include<fstream>
#include<iostream>
#include <experimental/optional>
std::tuple<std::ofstream, std::ofstream, std::ofstream>
set_ofstream_tuple()
{
auto streams = std::make_tuple(std::ofstream("out1.txt", std::ofstream::out),
std::ofstream("out2.txt", std::ofstream::out),
std::ofstream("out3.txt", std::ofstream::out));
auto& out1 = std::get<0>(streams);
auto& out2 = std::get<1>(streams);
auto& out3 = std::get<2>(streams);
out1 << "this is out1.txt" << std::endl;
out2 << "this is out2.txt" << std::endl;
out3 << "this is out3.txt" << std::endl;
return streams;
}
int main() {
std::experimental::optional<std::ofstream> out1, out2, out3;
std::tie(out1, out2, out3) = set_ofstream_tuple();
/// make use of there ofstreams more here
}