像這樣的代碼:
template <typename... type>
void print(type... pack) {
((std::cout << pack << " "), ...);
}
但我有如下引數:
{ {1, 2, 3}, {4, 5, 6} }
那么我怎樣才能將它傳遞給函式呢?或者,如何像這樣擴展引數包?
uj5u.com熱心網友回復:
但我有類似的引數:{ {1, 2, 3}, {4, 5, 6} }
你可以把它們打包成std::tuples
#include<iostream>
#include<tuple>
template <typename... Tuples>
void print_tuples(Tuples... tuples) {
(std::apply([](auto... args) {
((std::cout << args << " "), ...);
}, tuples), ...);
}
然后
print_tuples(std::tuple{1, 2, 3}, std::tuple{4, 5, 6});
演示
uj5u.com熱心網友回復:
我想您想initlizer_list連續擴展所有內容。
// for single initializer_list
template <typename T>
void print(std::initializer_list<T> args) {
for (const auto arg : args) {
std::cout << arg << " ";
}
}
// for nested initializer_list
template <typename T>
void print(std::initializer_list<std::initializer_list<T>> args) {
for (const auto arg : args) {
print(arg);
}
}
看演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/433973.html
上一篇:帶有自動模板引數的部分模板特化
