作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在编写一个使用可变模板函数的库,如下所示:
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;
}
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()
的返回值的情况下,有什么方法可以正确执行此操作?
最佳答案
不,您不可能在编译时生成依赖于仅在运行时已知的值的模板。您需要提前选择一些最大值,它是一个常量(有时不使用所有实例化),或者想办法使 maxArgs() 成为编译时常量。或者在使用时即时编译您的代码!
由于您拥有比我们更多的关于此代码的信息,也许您可以考虑是否实际上需要将其设为可变参数模板。考虑到模板参数的数量是在运行时确定的,似乎并非如此。编写一个完全由运行时决定的解决方案可能会更好,没有可变参数模板的东西。
关于c++11 - 可变模板函数的显式实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25698450/
我是一名优秀的程序员,十分优秀!