使用模板函数时未定义的引用

时间:2013-05-13 11:11:31

标签: c++ templates

以下代码简化为仅显示问题

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 个答案:

答案 0 :(得分:1)

那是因为您没有为此功能模板提供定义:

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

当您执行以下操作时,过载解析会选择哪个:

int t = numeric_cast<int>(s);

这个重载被选中,因为第二个numeric_cast模板需要一个非类型参数作为它的第一个模板参数,所以numeric_cast<int>不是实例化它的有效尝试。

相关问题