无法在循环中实例化泛型函数
Unable to instantiate generic function in a loop
>我有一些通用函数,看起来类似于
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
你应该能够让它工作。这有点语法地狱,但你可以管理它,我敢肯定。
相关文章:
- 模板化接口 - 创建一个泛型模板类以返回任何容器
- 如何在容器中指定模板化别名的泛型类型
- 具有模板专用化的泛型类型转换
- 使用泛型类型显式实例化函数模板
- C++ 具有非泛型参数的模板专用化
- 如何确保 "<<" 运算符适用于模板化 ADT 定义中的任何泛型类型?
- 无法在循环中实例化泛型函数
- boost::serialization-序列化从泛型属性/功能容器派生的类
- C++模板化类和泛型不起作用
- Boost:当缺少类型时,如何通过基指针序列化/反序列化泛型类型集合
- 在 C++ 中创建类模板的泛型实例
- 在泛型lambda表达式的所有实例化之间共享的局部静态变量
- 用于初始化派生类型的泛型 switch 语句
- 返回泛型容器,而不模板化类
- 确保模板化泛型参数的返回类型
- 泛型迭代器/指针初始化
- visual c++泛型类型实例化
- 我可以声明一个未知类型的特征矩阵吗,或者至少声明一个泛型矩阵并稍后实例化吗
- 每次实例化泛型类时增加编译时变量
- 泛型JNI类型实例化