【发布时间】:2014-10-31 03:35:03
【问题描述】:
我正在编写一个使用可变参数模板函数的库,如下所示:
template<typename ... T>
void func(T ... args) {
// ...
}
我需要确保为某些类型的该函数(即显式实例化)生成代码,如下所示:
template class func<int>;
template class func<int, int>;
template class func<int, int, int>;
// ...
int 参数的最大数量是非常量 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());
}
但这需要一个 const 值,因此它也无法编译。在不知道maxArgs() 的返回值的情况下,有什么方法可以正确地做到这一点?
【问题讨论】:
-
看来这可能是不可能的,编译器(特别是 gcc)如何使用省略号和 va_list 处理 C 风格的变量参数函数的代码生成?例如:
void func(int a, ...) { ... }
标签: c++11 code-generation instantiation variadic-templates