gpt4 book ai didi

c++ - 返回模板类的模板函数 - gcc 编译问题 - 错误 : expected unqualified-id before '<' token

转载 作者:行者123 更新时间:2023-11-27 23:15:10 25 4
gpt4 key购买 nike

我正在尝试使用基于模板的方法在 C++ 中实现基本的 2D vector 类。我的类(class)看起来像

template <typename T>
class Vector2 {
public:
union {
struct {
T x,y;
};
struct {
T lon, lat;
};
};

Vector2():x(0), y(0) {}
Vector2(const T c):x(c), y(c) {}
Vector2(const Vector2<T> & v):x(v.x), y(v.y){}
Vector2(const T _x, const T _y):x(_x), y(_y) {}
};

现在我想添加一些运算符,比如

inline template <typename T> Vector2<T> operator + (const Vector2<T>& a, const Vector2<T>& b){return Vector2<T>(a.x + b.x, a.y + b.y);}

对于开发,我目前使用 XCode 和 Apple 的 LLVM 编译器编译所有内容。因为我需要在 Linux 系统上额外编译,所以我也想使用 gcc。但是在我的 Linux 系统(Fedora,gcc 版本 4.1.2)和我的 mac(也是 gcc 版本 4.1.2)上编译都失败了,我得到了错误

错误:'<' 标记前应有不合格的 id

同样的错误发生在我基于模板的辅助函数上

inline template<typename T> Vector2<T> vector2Lerp(const Vector2<T>& A, const Vector2<T>& B,
const Vector2<T>& C, const Vector2<T>& D, const double x, const double y)
{
// use two helper Points
Vector2<T> P(A + x * (B - A));
Vector2<T> Q(C + x * (D - C));

// interpolate between helper Points
return P + y * (Q - P);
}

所以我的问题是,是否有人可以帮助我解决这个问题。感谢您的帮助!

最佳答案

您在错误的地方使用了 inline 关键字。在使用之前应该引入模板参数:

template <typename T> inline Vector2<T> operator + (....);

请注意,函数模板默认是内联,因此您可以省略它。

关于c++ - 返回模板类的模板函数 - gcc 编译问题 - 错误 : expected unqualified-id before '<' token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16802872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com