我看到一个blog post它使用了非类型可变参数模板(目前 gcc 不支持,仅 clang 支持)。
template <class T, size_t... Dimensions>
struct MultiDimArray { /* ... */ };
帖子中的示例编译正常,但我无法让它与函数模板一起工作。
谁能帮助找出正确的语法(如果存在的话)?
int max(int n) { return n; } // end condition
template <int... N> // replacing int... with typename... works
int max(int n, N... rest) // !! error: unknown type name 'N'
{
int tmp = max(rest...);
return n < tmp? tmp : n;
}
#include <iostream>
int main()
{
std::cout << max(3, 1, 4, 2, 5, 0) << std::endl;
}
最佳答案
这将打印出所有元素, get max 可以类似地实现
template <int N>
void foo(){
cout << N << endl;
}
template <int N, int M, int ... Rest>
void foo(){
cout << N << endl;
foo<M, Rest...>();
}
int main(){
foo<1, 5, 7>();
return 0;
}
关于c++ - C++11 中的非类型可变函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24169056/