尝试运行代码时遇到相同的链接器错误:
ld.lld: error: undefined symbol: Serialize::Archive& Serialize::Archive::operator>><double>(double&)
main.cpp(片段):
using namespace Serialize;
Archive arc(file, Archive::Save_Archive);
double test;
std::cout<<"Enter some data: ";
std::cin >> test;
arc >> test;
存档.hpp:
namespace Serialize{
template<typename T>
Archive& operator>>(T& obj);
}
存档.cpp:
namespace Serialize{
template<typename T>
Archive& Archive::operator>>(T& obj){};
}
我不认为我有任何命名空间问题,并且该运算符仅在 hpp 和 cpp 文件中定义和声明一次。
我尝试切换使用命名空间序列化和命名空间序列化,甚至只是这样做
Serialize::Archive arc(file, Serialize::Archive::Save_Archive);
您遇到的链接器错误与模板化函数的使用有关。在单独的 .cpp 文件中定义模板化函数时,编译器需要在实例化点(即模板与特定数据类型一起使用时)查看函数的实现(定义)。但是,由于模板实现通常在 .cpp 文件中找到,因此编译器在编译 main.cpp 文件时可能看不到实现。
要解决此问题,您可以为要在 main.cpp 文件中使用的数据类型显式实例化模板化函数。这将确保在编译 main.cpp 期间该函数的实现可用。
具体操作方法如下:
// Archive.hpp
namespace Serialize {
// ... (other code)
// Explicit instantiation of the templated operator>> for double
template Archive& operator>><double>(Archive& arc, double& obj);
}
// Archive.cpp
#include "Archive.hpp"
namespace Serialize {
// Implementation of the operator>> for double
Archive& Archive::operator>>(double& obj) {
// Implementation code here
return *this;
}
// Other implementations for different data types if needed
}
通过在 Archive.hpp 中显式实例化双精度数据类型的 operator>> 函数并在 Archive.cpp 中提供其实现,您可以确保链接器可以在链接阶段找到所需的函数定义。