問題描述
假設我有一個模板,它由一個類類型和許多參數類型參數化.匹配這些類型的一組參數存儲在一個元組中.如何將這些傳遞給類類型的構造函數?
Suppose I have a template which is parametrized by a class type and a number of argument types. a set of arguments matching these types are stored in a tuple. How can one pass these to a constructor of the class type?
幾乎在 C++11 代碼中:
In almost C++11 code:
template<typename T, typename... Args>
struct foo {
tuple<Args...> args;
T gen() { return T(get<0>(args), get<1>(args), ...); }
};
如何在不固定長度的情況下填充構造函數調用中的...
?
How can the ...
in the constructor call be filled without fixing the length?
我想我可以想出一些復雜的遞歸模板調用機制來做到這一點,但我不敢相信我是第一個想要這個的人,所以我想會有現成的解決方案這在那里,甚至可能在標準庫中.
I guess I could come up with some complicated mechanism of recursive template calls which does this, but I can't believe that I'm the first to want this, so I guess there will be ready-to-use solutions to this out there, perhaps even in the standard libraries.
推薦答案
C++17 有 std::make_from_tuple
為此:
C++17 has std::make_from_tuple
for this:
template <typename T, typename... Args>
struct foo
{
std::tuple<Args...> args;
T gen() { return std::make_from_tuple<T>(args); }
};
這篇關于來自元組的構造函數參數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!