我不太明白爲什麼這裏的代碼不能編譯。 應該可以調用DIST()像這樣:模板之間的隱式轉換
dist(GenericVec2<T>,GenericVec3<T>)
(然而可怕的,這可能是)。這個想法是GenericVec3參數被轉換運算符隱式轉換爲GenericVec2。 我這裏
C++ implicit type conversion with template
發現了這個問題,但我不太確定是否可以應用到我的問題(設置轉換操作符「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;
}
在此先感謝!
-Thomas
你'reinterpret_cast'打破嚴格走樣,並從一個比最後分配給其他一個'union'成員閱讀也UB。把代碼扔掉,從頭開始,它被打破了無法修復。如果你不明白我爲什麼要這樣說,那麼該閱讀一本好書。 –
我不能,這不是我的代碼,也不容易交換。我只需要知道如何讓它編譯(理想情況下,沒有做明確的dist(a,Vec2 {b})'轉換。 –
我已經刪除了union,因爲它不是實際問題的一部分不是很漂亮)原始問題仍然存在 –