无法在循环中实例化泛型函数

Unable to instantiate generic function in a loop

本文关键字:实例化 泛型 函数 循环      更新时间:2023-10-16

>我有一些通用函数,看起来类似于

template<int P>
struct foo {
    static const int value = ...;
};

现在,我想在循环中调用这个泛型函数。这样:

for (int i = 0; i < 100; ++i)
{
    auto bar = foo<i>::value;
}

但是我收到很多错误消息。喜欢

常量表达式中不使用"i"的值

int i 不是常数

我试图用以下方法修复它:

foo<(const int)i>::value;

但无济于事。那么,这有什么问题,我怎样才能让它工作?

你不能

这样做。

for (int i = 0; i < 100; ++i)
{
  auto bar = foo<i>::value;
}

我需要一个常量表达式,以便编译器在编译程序时可以为它生成代码。

以下是对常量表达式的详尽解释:http://en.cppreference.com/w/cpp/language/constant_expression


这是该网站的一个片段:

int n = 1;
std::array<int, n> a1; // error: n is not a constant expression
const int cn = 2;
std::array<int, cn> a2; // OK: cn is a constant expression

因此,为了在编译时实现它,您需要使用可变参数模板将循环转换为模板递归。

如果你阅读这个例子,也许你可以理解你需要做得更好:

// Example program
#include <iostream>
#include <string>
template<int P>
struct foo
{
    static const int value = P;
};
template <int TIndex>
int call() 
{
  return foo<TIndex>::value;
}
template <int TIndex, int TIndex2, int ...Rest>
int call ()
{
 return call<TIndex>() + call<TIndex2, Rest...>();
}
int main()
{
  std::cout << "Test: " << call<1, 2>()  << "n"; // prints "Test: 3"
}

Nicky C发布了另一个问题的链接。它有一个很好的答案,我觉得在这里复制它不合适。看看我上面的工作示例,然后看看这里的答案:

https://stackoverflow.com/a/11081785/493298

你应该能够让它工作。这有点语法地狱,但你可以管理它,我敢肯定。