2013-05-13 67 views
1

時,下面的代碼被簡化爲只顯示問題未定義參考使用模板函數

template <unsigned bits_count, typename ut_t = unsigned short, typename st_t = short, typename udt_t = unsigned, typename sdt_t = int> 
struct int_t 
{ 
    typedef ut_t  ut; 

    ut comp[bits_count/(sizeof(ut) * 8)]; 
}; 

template<typename ot, typename it> 
inline ot& mathx_int_from_t_to_niv(const it& value, ot& result) 
{ 
    typedef typename it::ut ut; 

    result = ot(0); 

    if (sizeof(ot) <= sizeof(ut)) return result = ot(value.comp[0]); 

    return result = *(ot*)value.comp; 
} 

template <typename ot, typename it> 
ot numeric_cast(const it& value); 

template<unsigned bits_count, typename ut_t, typename st_t, typename udt_t, typename sdt_t> 
inline int numeric_cast(const int_t<bits_count, ut_t, st_t, udt_t, sdt_t>& value) 
{ 
    typedef int_t<bits_count, ut_t, st_t, udt_t, sdt_t> it; 
    int result; 

    return mathx_int_from_t_to_niv<int, it>(value, result); 
} 

typedef int_t<128> int128; 

int main() 
{ 
    int128 s = { { 0 } }; 
    s.comp[0] = -1; 

    int t = numeric_cast<int>(s); 
} 

上面的代碼編譯錯誤undefined reference to 'int numeric_cast<int, int_t<128u, unsigned short, short, unsigned int, int> >(int_t<128u, unsigned short, short, unsigned int, int> const&)'

我不明白爲什麼GCC產生這個錯誤,當我明確寫出numeric_cast的部分專業化,它說這是不允許的,當我提供一個超載它說未定義的參考。

回答

1

那是因爲你還沒有提供這個函數模板的定義:

template <typename ot, typename it> 
ot numeric_cast(const it& value); 

它得到通過重載拿起當你這樣做:

int t = numeric_cast<int>(s); 

而這種超載得到回升,因爲第二numeric_cast模板需要一個非類型參數作爲其第一個模板參數,因此numeric_cast<int>不是有效的實例化它的嘗試。

+0

聲明應該有幾種類型的多重定義。我怎樣才能解決這個問題,而沒有明確提供這個聲明的實現? – 2013-05-13 11:18:23

+0

@Muhammadalaa:我不確定我的理解。你爲什麼要爲'numeric_cast <>'提供一個明確的'int'參數(即'numeric_cast ')? – 2013-05-13 11:20:51

+0

'numeric_cast'應該在源和目標類型之間進行轉換,源是本地類型或'int_t',目標是'int_t'或本地類型,FYI也有'uint_t'和'float_t'這就是爲什麼'numeric_cast'是通用的。 – 2013-05-13 11:23:41