i'm writing a Point class in c++ and use templates for this. But i have a compile error that i don't understand. I wrote a minimal example of the problem:
#include <array>
#include <vector>
#include <iostream>
template <typename T, int DIM>
class Point
{
private:
std::array<T, DIM> values;
public:
template <int ROW>
T get()
{
return values.at(ROW);
};
};
template <typename T>
class Field
{
public:
T print(std::vector<Point<T, 3> >& vec)
{
for (auto it : vec)
{
T bla = it.get<1>(); // the error line 27
}
};
};
int main(int argc,
char* argv[])
{
Point<double, 3> p;
double val = p.get<1>();
std::cout << val << std::endl;
Field<int> f;
std::vector<Point<int, 3> > vec;
f.print(vec);
return 0;
}
I compile with
g++ main2.cpp -std=c++11
and the output is
main2.cpp: In member function ‘T Field<T>::print(std::vector<Point<T, 3> >&)’:
main2.cpp:27:33: error: expected primary-expression before ‘)’ token
T bla = it.get< 1 >();
^
main2.cpp: In instantiation of ‘T Field<T>::print(std::vector<Point<T, 3> >&) [with T = int]’:
main2.cpp:41:16: required from here
main2.cpp:27:27: error: invalid operands of types ‘<unresolved overloaded function type>’ and ‘int’ to binary ‘operator<’
T bla = it.get< 1 >();
Does someone know why the error occurs and how to solve it?
Thank you.
Since it.get<1>()
is dependent on a template parameter, you need to tell the compiler that get
is a template so that it can be parsed correctly:
T bla = it.template get<1>();
Additionally, you don't return anything from that print
function, even though the declaration says it should return a T
.
See this question for more detail about the template
keyword in this context.
Change the line
T bla = it.get<1>(); // the error line 27
to:
T bla = it.template get<1>(); // the error line 27
You need the template
keyword to access template member functions if the class they're in is itself a template class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With