gpt4 book ai didi

c++11 - 可变模板函数的显式实例化

转载 作者:行者123 更新时间:2023-12-03 08:13:39 24 4
gpt4 key购买 nike

我正在编写一个使用可变模板函数的库,如下所示:

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() 的返回值的情况下,有什么方法可以正确执行此操作?

最佳答案

不,您不可能在编译时生成依赖于仅在运行时已知的值的模板。您需要提前选择一些最大值,它是一个常量(有时不使用所有实例化),或者想办法使 maxArgs() 成为编译时常量。或者在使用时即时编译您的代码!

由于您拥有比我们更多的关于此代码的信息,也许您可​​以考虑是否实际上需要将其设为可变参数模板。考虑到模板参数的数量是在运行时确定的,似乎并非如此。编写一个完全由运行时决定的解决方案可能会更好,没有可变参数模板的东西。

关于c++11 - 可变模板函数的显式实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25698450/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com