如何使编译器意识到模板结构

How to make the compiler aware of templated struct?

本文关键字:结构 意识到 何使 编译器      更新时间:2023-10-16

我正试图实现在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链接的骗局击中了它的头部,但对于非模板类。这个答案显示了当类被模板化时的语法。