sanchises sanchises - 1 month ago 4
C++ Question

How to make the compiler aware of templated struct?

I am trying to implement an answer given on my question over at CodeReview.SE. Basically, I want to access some static variables in a templated struct. Consider the following example code:



#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;
}


The compiler does not recognize that I want
Data<n>
to be available in the program - however, it recognizes the initial
getBar<n>
function just fine as is evident from the error message:

undefined reference to `Data<2>::bar'


How do I tell the compiler to make the templated struct available as well?

Answer

Static class variables must be given memory allocation. Add this:

template<const int idx>
int Data<idx>::bar = 0;

Demo

Edit: The dupe linked by NathanOliver hits it on the head, but for non-templated classes. This answer shows the syntax when the class is templated. minor difference, but still useful.