我正在用 C++ 编写一个 Point 类并为此使用模板。但是我有一个我不明白的编译错误。我写了一个问题的最小例子:
#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;
}
Run Code Online (Sandbox Code Playgroud)
我编译
g++ main2.cpp -std=c++11
Run Code Online (Sandbox Code Playgroud)
输出是
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 >();
Run Code Online (Sandbox Code Playgroud)
有人知道错误发生的原因以及如何解决吗?
谢谢你。
由于it.get<1>()依赖于模板参数,您需要告诉编译器这get是一个模板,以便可以正确解析它:
T bla = it.template get<1>();
Run Code Online (Sandbox Code Playgroud)
此外,您不会从该print函数返回任何内容,即使声明说它应该返回一个T.
有关此上下文中关键字的更多详细信息,请参阅此问题template。
| 归档时间: |
|
| 查看次数: |
1327 次 |
| 最近记录: |