编译 MS VC 时出现 GCC 错误++带有模板的代码
我们正在获取一些为 Visual Studio 2008 编写的代码,并尝试使用 gcc 对其进行编译。我们在以下代码中遇到了错误(简化为必要的内容):
template<int R, int C, typename T>
struct Vector
{
template <typename TRes>
TRes magnitude() const
{
return 0;
}
};
struct A
{
typedef Vector<3,1,int> NodeVector;
};
template<class T>
struct B
{
void foo()
{
typename T::NodeVector x;
x.magnitude<double>(); //< error here
}
};
...
B<A> test;
test.foo();
GCC 说
error: expected primary-expression before 'double'
error: expected `;' before 'double'
Can you suggest the error to me?什么是交叉编译器解决方案?
多谢!
we're taking some code written for Visual Studio 2008 and try to compile it with gcc. We experienced an error in the following code (simplified to what's necessary):
template<int R, int C, typename T>
struct Vector
{
template <typename TRes>
TRes magnitude() const
{
return 0;
}
};
struct A
{
typedef Vector<3,1,int> NodeVector;
};
template<class T>
struct B
{
void foo()
{
typename T::NodeVector x;
x.magnitude<double>(); //< error here
}
};
...
B<A> test;
test.foo();
GCC says
error: expected primary-expression before 'double'
error: expected `;' before 'double'
Can you explain the error to me? What's a cross-compiler solution?
Thanks a lot!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是,由于 C++ 编译器不知道
T
的实际类型(更不用说T::NodeVector
),它也不知道magnitude 应该是一个模板,您需要明确指定:
否则 C++ 会将标记解析为
x
、operator.
、magnitude
、operator<
、double
、operator>
…顺便说一句,GCC 是对的,MSVC++ 在这些问题上是出了名的宽松。
The problem is that since the C++ compiler doesn’t know the actual type of
T
(let aloneT::NodeVector
it doesn’t know thatmagnitude
is supposed to be a template. You need to specify that explicitly:Otherwise C++ will parse the tokens as
x
,operator.
,magnitude
,operator<
,double
,operator>
…The GCC is right, by the way. MSVC++ is notoriously lax on such matters.
在 B 点,它无法知道 x 是什么类型,并且该大小将是一个模板函数,因此您需要首先将其声明为 1。
At the point of B it has no way to know what type x is, and that magnitude will be a template function so you need to declare it as one first.