繁体   English   中英

使用模板功能时未定义的参考

[英]undefined reference when using template function

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

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&)'错误, 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编写部分专业化时,它说这是不允许的,当我提供重载时,它说的是未定义的引用。

这是因为您尚未提供此功能模板的定义:

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

当执行以下操作时,将由过载解析选择:

int t = numeric_cast<int>(s);

之所以会选择此重载,是因为第二个numeric_cast模板期望将非类型参数作为其第一个模板参数,因此, numeric_cast<int>并不是将其实例化的有效尝试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM