我有一个带有整数模板参数的函数:
template<int N>
int func() {
return N;
}
我为我可能提供的所有模板参数显式实例化模板:template int func<1>();
template int func<2>();
template int func<3>();
//...
然后我想用运行时指定的整数 n
调用 func ://This code does not compile
int main() {
int n;
std::cin >> n;
// check that n is one of the allowed values
std::cout << func<n>(); // can fail if given a bad n
return 0;
}
是否可以对此代码进行修改以调用 func<n>()
与 n
在运行时指定(比如 0 < n < 20
)?
最佳答案
是的,这是可能的,但不是您尝试的方式,因为模板语法如 F<N>
需要编译时值。但是,一旦实例化,它们就是常规函数,您可以将函数指针指向它们,或者将它们放入 std::function 等。
例如,您可以为允许通过运行时索引访问的函数指针构建一个数组,如下所示:
template <int N>
int f() { return N; } // your function(s)
int main()
{
using Func = int(*)();
Func funcs[]{f<0>, f<1>, f<2>, }; // array of instances of f
// call a function via runtime value stored in n:
int n = 2;
funcs[n]();
}
关于c++ - 您可以使用运行时指定的变量调用编译时实例化模板函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63209580/