【发布时间】:2015-07-27 17:46:43
【问题描述】:
我正在编写一个数学库。我使用 C++ 的模板来完成它。
有两种代码。一个好吗?但是另一个不好?为什么?
错误日志:
../test_vector/main.cpp:98:10: 错误:重载 'operator*' 必须至少有一个类或枚举类型的参数 内联 T 运算符*(float s,const T &t)
#include <cmath>
namespace gqm
{
template <typename T>
struct vector2 {
vector2() {}
vector2(T x, T y) : x(x), y(y) {}
vector2 operator*(float s) const
{
return vector2(x * s, y * s);
}
T x;
T y;
};
//it works good!
template <typename T>
inline T operator*(float s,const T &t)
{
return t.operator*(s);
}
//it do not works!Why?
//template <typename T>
//inline T operator*(float s,const T &t)
//{
// return t*s;
//}
typedef vector2<float> vec2;
}//namespace gqm
int main()
{
gqm::vec2 v2 = 0.5 * gqm::vec2(1.0,1.0);
return 0;
}
【问题讨论】:
-
你用的是什么编译器? GCC 4.8.4 没问题
-
尝试编译您实际发布的内容......可能在“真实代码”中您输入了“不工作!”部分位于
vector2的类定义中 -
或者你用内置类型实例化了模板