我写一个使用可变参数为模板的功能,像这样一个图书馆:的可变参数模板显式实例化功能
template<typename ... T>
void func(T ... args) {
// ...
}
我需要确保在该函数中生成的代码(即显式实例化)的某些类型,像这样:
template class func<int>;
template class func<int, int>;
template class func<int, int, int>;
// ...
其中int
参数的最大数是一个非const maxArgs()
(我无法改变这个,因为它是一个外部函数)。我试过以下内容:
template<typename ... T>
void f(size_t max, T ... args) { // Generates "infinitely"
if (sizeof...(T) < max) {
func(args...);
f(max, args..., 0);
}
}
int main(int argc, char** argv) {
f(maxArgs(), 0);
// ...
return 0;
}
但是,编译器对函数生成递归没有适当的基本情况,所以无法编译。我已经使用非类型模板,像这样(使用一些代码here)也试过:
template<int ...> struct seq { };
template<int N, int ... Ns> struct gens : gens<N-1, N-1, Ns...> { };
template<int ... Ns> struct gens<0, Ns...> { typedef seq<Ns...> type; };
std::vector<int> params;
template<int ... Ns>
void f(seq<Ns...>) {
test(std::get<Ns>(params)...);
}
void instantiate(size_t max) {
for (int i = 1; i < max; ++i) {
for (int j = 0; j < i; ++j) {
params.push_back(0);
}
f(typename gens<i>::type()); // Fails to compile -- i is not const
params.clear();
}
}
int main(int argc, char** argv) {
instantiate(maxArgs());
}
但这需要一个常量的值,所以无法编译为好。有没有办法正确地做到这一点,不知道maxArgs()
的返回值?
鉴于这可能是不可能的,编译器(特别是gcc)如何使用省略号和va_list处理C风格变量参数函数的代码生成?例如:'void func(int a,...){...}' – 2014-09-06 08:55:53