2010-05-21 74 views
0

可以說,我正在寫一個某種類型轉換操作符的,我想用它這樣:多參數模板函數和重載歧義錯誤

SomeType a; 
AnotherType b = conv<AnotherType>(a); 

首先,我寫的底座(默認)功能:

template <typename T, typename U> 
inline T conv(const U& a) 
{ 
    return T(a); 
} 

完全專業化(或非模板超載)是沒有問題的,但是,當我想要做這樣的事情:

template <typename T> 
inline Point<T> conv(const Ipoint& p) 
{ 
    return Point<T>(p.x, p.y); 
} 

我不能寫入從IPOINT由於歧義任何更多的轉換函數(給FunkyPoint < T>例如),並且我結束了一個笨拙用法:

Ipoint a; 
Point<double> b = conv<double>(a); //ugly! 
//Point<double> b = conv<Point<double> >(a); //I want that, but it (obviously) does not compile. 

有沒有這樣做的任何方式很好嗎?

+1

爲什麼不重寫構造函數或轉換操作符? – kennytm 2010-05-21 19:56:55

+0

因爲我無法訪問上述結構(Ipoint/Point < T >)。 – maticus 2010-05-21 20:11:35

回答

3

在類模板實現身體,那麼你就可以部分地專注:

 
template < typename T, typename U > 
struct convert 
{ 
    static T apply(U const& u) { return T(u); } 
};

template < typename T, typename U > T conv(U const& u) { return convert<T,U>::apply(u); }

template < typename T > struct convert<Point<T>, Ipoint> { static Point apply(Ipoint const& u) { return Point(u.x, u.y); } };

應該工作,但未經測試。