如何使编译器意识到模板结构
How to make the compiler aware of templated struct?
我正试图实现在CodeReview.SE上给出的问题的答案。基本上,我想访问模板结构中的一些静态变量。考虑下面的示例代码:
#include <iostream>
using namespace std;
template<const int idx>
struct Data{
static int bar;
};
template<const int idx>
int getBar(){
return Data<idx>::bar;
}
int main() {
const int n = 2; // Arbitrary number
cout << getBar<n>();
return 0;
}
编译器不知道我想让Data<n>
在程序中可用——然而,它可以很好地识别初始的getBar<n>
函数,这从错误消息中可以看出:
undefined reference to `Data<2>::bar'
我如何告诉编译器使模板结构也可用?
静态类变量必须分配内存。添加这个:
template<const int idx>
int Data<idx>::bar = 0;
演示编辑:由NathanOliver链接的骗局击中了它的头部,但对于非模板类。这个答案显示了当类被模板化时的语法。
相关文章:
- 如何将结构插入到集合中并打印集合的成员
- 将结构发送到函数C++
- Windows 将标准的 C 文件结构注入到正在运行的进程中
- C++将结构复制到另一个程序的资源
- 如何将带指针的结构插入到映射中
- C 通过 UART 将结构发送到 Python
- 如何让指针的深层副本将内部结构发送到内核?
- 使用 aligned_malloc 和 memcpy 多次将结构复制到指针
- C++ push_back() 一个结构体到一个向量中
- 多线程和共享资源:使用C++定期将数据从缓冲区(数据结构)复制到文件
- 将带有字符数组的结构复制到字符数组
- 访问嵌套结构的数据成员并将结构传递到功能C
- C 结构/联合到C#结构
- 错误将结构复制到同一类型的另一种
- 如何使用参数将函数从一个结构传递到另一个结构中的另一个函数
- C :将结构传递到函数,无法理解语法
- 将包含位字段和动态数据的结构复制到 Char 数组缓冲区中
- 将结构追加到矢量<uint8_t>
- 如何读写结构向量到文件
- 如何使编译器意识到模板结构