c++ - 您可以使用运行时指定的变量调用编译时实例化模板函数吗?

标签 c++ templates

我有一个带有整数模板参数的函数:

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/

相关文章:

c++ - 强制特定类型的函数模板/函数重载

c++ - 显式模板实例化问题

c++ - 带有切换实例化模板的枚举的工厂

C++制作一个松散类型的语言解析器

c++ - RAII std::vector 设计难题

c++ - 如何在C++中正确使用#ifndef#define #endif

c++ - Emacs 右对齐 ')'

c++ - 删除时会调用模板参数的模板类的析构函数吗?

python - 如何在Cheetah for Python中正确使用多维字典?

C++ - 写入 VS2010 中的特定输出窗口 Pane