2013-05-13 59 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