5

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.

Perry Black
  • 83
  • 1
  • 6

2 Answers2

5

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.

Community
  • 1
  • 1
TartanLlama
  • 59,364
  • 11
  • 141
  • 183
1

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.

Smeeheey
  • 9,162
  • 16
  • 37