How to make the compiler aware of templated struct?
本问题已经有最佳答案,请猛点这里访问。
我正在尝试在CodeReview.SE上针对我的问题给出答案。 基本上,我想在模板化结构中访问一些静态变量。 考虑以下示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #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; } |
编译器无法识别出我希望
1 | undefined reference to `Data<2>::bar' |
我如何告诉编译器也使模板化结构可用?
必须给静态类变量分配内存。 添加此:
1 2 | template<const int idx> int Data<idx>::bar = 0; |
演示版
编辑:NathanOliver链接的骗子将其击中头部,但对于非模板类。 该答案显示了在对类进行模板化时的语法。 差异不大,但仍然有用。