這是一個簡短的程序,用於使用代碼根據Johannes Schaub - litb和Luc Danton的答案打印元組。C++ 11可變參數模板:默認索引數組值
#include <iostream>
#include <tuple>
template<int ...>
struct seq { };
template<int N, int ...S>
struct gens : gens<N-1, N-1, S...> { };
template<int ...S>
struct gens<0, S...> {
typedef seq<S...> type;
};
template <int ...S, typename ...T>
void print(const std::tuple<T...> & tup, seq<S...> s) {
int res[] = { (std::cout << std::get<S>(tup) << " ", 0)... };
std::cout << std::endl;
}
int main() {
std::tuple<double, int, char> tup(1.5, 100, 'c');
print(tup, gens<std::tuple_size<decltype(tup)>::value >::type());
return 0;
}
打印的第二個參數將總是始終gens<N>::type()
,其中N
是元組的大小。我試圖避開了第二個參數通過提供一個默認參數打印:
template <int ...S, typename ...T>
void print(const std::tuple<T...> & tup, seq<S...> s = gens<std::tuple_size<decltype(tup)>::value >::type()) {
int res[] = { (std::cout << std::get<S>(tup) << " ", 0)... };
std::cout << std::endl;
}
然而,結果是一個編譯器錯誤:
tmp5.cpp: In function ‘void print(const std::tuple<_Elements ...>&, seq) [with int ...S = {}; T = {double, int, char}]’:
tmp5.cpp:23:12: error: incomplete type ‘std::tuple_size&>’ used in nested name specifier
你知道有什麼方法可以提供S...
無函數的第二個參數如print
?
鏗鏘樣式的評論真的很討厭。 –
@ JohannesSchaub-litb:我必須承認,我非常喜歡這種呈現編譯錯誤的方式(當時只有幾個人......) –
太糟糕了。我正在處理異構元組(元組,array ,...>',其內容可以全部發送到模板函數'template array f(array )'以產生新的我想現在,我將把序列設置爲一個常量表達式,以避免在第二個參數中出現重複的「gens」代碼。 –
user