假設我有以下內容tuple:
std::tuple<int, int, int> setVals(int val)
{
return std::make_tuple(val, val, val);
}
用這個進行結構化系結真的很好:auto [x, y, z] = setVals(42);
是否有可能有某種可變引數簽名setVals,所以我可以使用任意數量的變數進行結構化系結?例如,auto [x, y] = setVals(42);或auto [x, y, z, x2, y2, z2] = setVals(42);
我知道我可以只使用可變引數函式模板,我可以在其中宣告一些整數并將它們作為參考傳遞,但是結構化系結非常方便,以至于我想知道我剛剛展示的內容是否可行。如果這個問題不好,我很抱歉。
uj5u.com熱心網友回復:
您可以創建一個您想要的函式,但您必須指定元組將具有的元素數量作為模板引數。這會給你這樣的代碼:
// does the actual creation
template <typename T, std::size_t... Is>
auto create_tuple_helper(const T& initial_value, std::index_sequence<Is...>)
{
// this ueses the comma expression to discard Is and use initial_value instead for each element
return std::tuple{(void(Is), initial_value)...};
// void(Is) is used to get rid of a warning for an unused value
}
// this is a wrapper and makes it easy to call the helper function
template <std::size_t N, typename T>
auto create_tuple(const T& initial_value)
{
return create_tuple_helper(initial_value, std::make_index_sequence<N>{});
}
int main()
{
auto [a, b, c, d] = create_tuple<4>(42);
std::cout << d;
}
活生生的例子
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/515132.html
標籤:C 模板
