使用模板函数时未定义的引用
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&)'
我不明白为什么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>
不是一个有效的尝试来实例化它。
相关文章:
- 对C宏的未定义引用,但在定义它时会出现重新定义错误
- 编译时的 CImg 库返回对"__imp_SetDIBitsToDevice"的未定义引用
- 对Py_Initialize()的未定义引用
- 使用mysql c++连接器的未定义引用
- 对 Scalar ::Scalar() 的未定义引用
- 对复制 CTOR 和 CTOR 的未定义引用
- 对显式实例化的模板函数的未定义引用
- TensorRT (C++ API) 对"createNvOnnxParser_INTERNAL"的未定义引用
- 2个模板化类的非模板友元函数未定义引用错误
- 编译 libfluid 样本控制器时对"event_base_del_virtual"的未定义引用
- 获取对function_name的未定义引用
- 对 'std::thread::_M_start_thread CMake 的未定义引用进行基准测试
- 对结构方法的未定义引用
- 使用内联函数 c++ 的未定义引用
- 对 CMake 中'cudaRegisterLinkedBinary'链接错误的未定义引用?
- 对 DLOPEN 的未定义引用
- QT C++中对全局变量的未定义引用
- 快速数学导致对"__pow_finite"的未定义引用
- 对 boost::system::d etail::system_category_instance 的未定义引用,从
- OpenCV 3.4.3 中对 'cv::String::d eallocate()' 错误的未定义引用