我不太明白为什么这里的代码不能编译。应该可以像这样调用 dist() :
dist(GenericVec2<T>,GenericVec3<T>)
(无论这可能多么可怕)。这个想法是 GenericVec3 参数被转换运算符隐式转换为 GenericVec2。我在这里找到了这个问题
,但我不太确定它是否可以应用于我的问题(将转换运算符设置为 " friend
" 不起作用)。VS 输出以下错误:
error C2672: 'dist': no matching overloaded function found
error C2784: 'F dist(const GenericVec2<F> &,const GenericVec2<F> &)': could not deduce template argument for 'const GenericVec2<F> &' from 'Vec3'
note: see declaration of 'dist'
这是我的代码:
#include <iostream>
template<typename F> struct GenericVec2
{
GenericVec2<F>::GenericVec2(F _x = 0, F _y = 0) : x(_x), y(_y) {}
F x;
F y;
};
using Vec2 = GenericVec2<float>;
template<typename F> struct GenericVec3
{
GenericVec3<F>::GenericVec3(F _x = 0, F _y = 0, F _z = 0) : x(_x), y(_y), z(_z) {}
operator GenericVec2<F>() { return *reinterpret_cast<GenericVec2<F>*>(&x); }
operator const GenericVec2<F>() const { return *reinterpret_cast<const GenericVec2<F>*>(&x); }
F x;
F y;
F z;
};
using Vec3 = GenericVec3<float>;
template<typename F> F dist(const GenericVec2<F>& a, const GenericVec2<F>& b)
{
return std::hypot(a.x - b.x, a.y - b.y);
}
int main()
{
Vec2 a{ 2.0f, 3.0f };
Vec3 b{ 1.0f, 1.0f, 1.0f };
Vec2 c = b;
float d = dist(a, Vec2{ b }); // works
float e = dist(a, b); // doesn't compile
std::cin.ignore();
return 0;
}
提前致谢!
-托马斯