这就是我想要做的:
// base case
void f() {}
template <typename T, typename... Ts>
void f() {
// do something with T
f<Ts...>();
}
int main() {
f<int, float, char>();
return 0;
}
它不编译:
prog.cpp: In instantiation of ‘void f() [with T = char; Ts = {}]’:
prog.cpp:6:5: recursively required from ‘void f() [with T = float; Ts = {char}]’
prog.cpp:6:5: required from ‘void f() [with T = int; Ts = {float, char}]’
prog.cpp:10:25: required from here
prog.cpp:6:5: error: no matching function for call to ‘f()’
prog.cpp:6:5: note: candidate is:
prog.cpp:4:6: note: template<class T, class ... Ts> void f()
prog.cpp:4:6: note: template argument deduction/substitution failed:
prog.cpp:6:5: note: couldn't deduce template parameter ‘T’
该线程显示了解决此问题的方法,但基本案例必须是模板。我不太喜欢它,因为据我了解,我将不得不复制与 T 一起使用的代码。有没有办法避免这种情况?
到目前为止,我想出了两个解决方案(http://ideone.com/nPqU0l):
template <typename...> struct types_helper {};
// base case
void f(types_helper<>) {}
template <typename T, typename... Ts>
void f(types_helper<T, Ts...>) {
// do something with T
f(types_helper<Ts...>());
}
int main() {
f(types_helper<int, float, char>());
return 0;
}
#include <type_traits>
struct end_of_list;
template <typename T>
void f() {
static_assert(std::is_same<T, end_of_list>::value, "error");
}
template <typename T1, typename T2, typename... Ts>
void f() {
// do something with T
f<T2, Ts...>();
}
int main() {
f<int, float, char, end_of_list>();
return 0;
}
我想知道是否有更好的方法来做到这一点。