Ale*_*ino 1 c++ tuples variadic-templates c++17
如果我把整个概念弄错了,我很抱歉,但我正在尝试将一个元组作为实际对象的容器,只有在销毁这些对象时,这些对象才会超出范围。
我目前有这个:
class MiniThread {
public:
~MiniThread() {
if (m_thread) {
if (m_thread->joinable())
m_thread->join();
delete m_thread;
}
}
void join()
{
if (m_thread == nullptr)
return;
m_thread->join();
m_thread = nullptr;
}
template<typename F, typename... Args>
void run(F func, Args... args)
{
if (m_thread != nullptr)
join();
auto tuple = std::forward_as_tuple(args...);
m_thread = new std::thread([=]() {
__try
{
std::apply(func, tuple);
}
__except (CrashDump::GenerateDump(GetExceptionInformation()))
{
// TODO: log.
exit(1);
}
});
m_started = true;
}
bool started() const { return m_started; }
private:
std::thread *m_thread = nullptr;
bool m_started = false;
};
std::string getString()
{
return std::string("sono");
}
int main()
{
auto test = [&](std::string seila, const std::string& po, std::promise<int>* p)
{
std::cout << seila.c_str() << std::endl;
std::cout << po.c_str() << std::endl;
p->set_value(10);
};
std::promise<int> p;
std::future<int> f;
MiniThread thread;
std::string hello = "hello";
std::string seilapo = "seilapo";
f = p.get_future();
thread.run(test, getString(), "how are you", &p);
thread.join();
int ftest = f.get();
std::cout << ftest << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
到线程运行时,args它们不再可靠。他们已经被摧毁了。所以我想知道是否有办法在线程的调用中按值复制它们。我已经尝试将可变参数移动到元组中,但是元组总是以rvalues相同的方式呈现并失败。
这个:
auto tuple = std::forward_as_tuple(args...);
Run Code Online (Sandbox Code Playgroud)
创建一个引用元组到args...That's what forward_as_tuple's job is。然后,您将按值捕获该引用元组:
m_thread = new std::thread([=]{ /* ... */ });
Run Code Online (Sandbox Code Playgroud)
因此,一旦您的论点超出范围,您就只能保留对它们的引用……这将悬而未决。
但你实际上并不......根本不需要一个元组。只需复制参数本身:
m_thread = std::thread([=]() {
func(args...); // func and args, no tuple here
});
Run Code Online (Sandbox Code Playgroud)
也不要写new thread——thread已经是句柄类型了,就创建一个。
以上复制了参数。如果你想移动它们,那么在 C++17 中,是的,你需要有一个tuple并使用std::apply. 但不是forward_as_tuple......只是make_tuple:
m_thread = std::thread([func, args=std::make_tuple(std::move(args)...)]() mutable {
std::apply(func, std::move(args));
});
Run Code Online (Sandbox Code Playgroud)
在 C++20 中,您将不再需要tuple,并且可以编写一个包扩展:
m_thread = std::thread([func, ...args=std::move(args)]() mutable {
func(std::move(args)...);
});
Run Code Online (Sandbox Code Playgroud)