Monday 14 March 2016

c++ - .template (dot-template) construction usage








I've come across a strange segment of code:



#include 

template
struct Collection {
int data[N];

Collection() {

for(int i = 0; i < N; ++i) {
data[i] = 0;
}
};

void SetValue(int v) {
for(int i = 0; i < N; ++i) {
data[i] = v;
}
};


template
int GetValue(void) const {
return data[I];
};
};

template
void printElement(Collection const & c) {
std::cout << c.template GetValue() << std::endl; /// doesn't compile without ".template"

}

int main() {
Collection<10> myc;
myc.SetValue(5);
printElement<10, 2>(myc);
return 0;
}



It is not compiled without .template keyword in printElement function. I've never seen this before and I don't understand what is needed for. Trying to remove it, I got a lot of template-related compilation errors. So my question is when such a construction is used? Is it common?

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...