2017-05-31 52 views
1

我不太明白爲什麼這裏的代碼不能編譯。 應該可以調用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

+2

你'reinterpret_cast'打破嚴格走樣,並從一個比最後分配給其他一個'union'成員閱讀也UB。把代碼扔掉,從頭開始,它被打破了無法修復。如果你不明白我爲什麼要這樣說,那麼該閱讀一本好書。 –

+0

我不能,這不是我的代碼,也不容易交換。我只需要知道如何讓它編譯(理想情況下,沒有做明確的dist(a,Vec2 {b})'轉換。 –

+0

我已經刪除了union,因爲它不是實際問題的一部分不是很漂亮)原始問題仍然存在 –

回答

0

問題是,在

template<typename F> F dist(const GenericVec2<F>& a, const GenericVec2<F>& b) 

你不能從GenericVec2<float>推斷第二個參數。 一種解決方案是使函數模板非由於friend

template<typename F> struct GenericVec2 
{ 
    GenericVec2<F>::GenericVec2(F _x = 0, F _y = 0) : x(_x), y(_y) {} 


    friend F dist(const GenericVec2& a, const GenericVec2& b) 
    { 
     return std::hypot(a.x - b.x, a.y - b.y); 
    } 

    F x; 
    F y; 
}; 
+0

工作的很好!我想看看'friend'關鍵字,我猜... –

0

爲了隱式轉換是可能的目標類應具有接收源類型(或類型從源類型轉換)作爲參數的構造函數。在GenericVec3中定義的鑄造操作員用於顯式鑄造操作。

所以,你應該定義下面的構造在GenericVec2

GenericVec2(const GenericVec3<F>& v3) { ... }

+0

這裏沒有什麼變化,和以前一樣的錯誤,現在的代碼是:https://pastebin.com/yzTECFHn –