【发布时间】:2020-08-28 15:03:51
【问题描述】:
在尝试使用我编写的模板化运算符时,我收到了来自 clang++ 的链接器错误。
错误是:
main.cpp:(.text+0xfe): undefined reference to `operator<<(std::ostream&, schematic<130ul, 128ul, 130ul> const&)'
main.cpp:(.text+0x28c): undefined reference to `operator<<(std::ostream&, schematic<130ul, 1ul, 130ul> const&)'
现在在我继续之前或者您将其标记为重复之前:我知道您不能将模板定义放在单独的 .cpp 文件中,而我没有这样做。运算符的定义是在一个单独的头文件中,该文件包含在其声明中,如this answer 中所述。由于它仍然给我链接器错误,我在这里问。
代码
main.cpp
// includes
int main(int argc, char const* argv[])
{
// ...
switch (/* call */)
{
case /* one */:
fout << mapArtFlat(/* ctor params */).exportScematic();
break;
case /* another */:
fout << mapArtStaircase(/* ctor params */).exportSchematic();
break;
}
return 0;
}
原理图.h
#ifndef SCHEMATIC_H
#define SCHEMATIC_H
// includes
template <std::size_t W, std::size_t H, std::size_t L>
class schematic
{
friend std::ostream& operator<<(std::ostream&, const schematic<W,H,L>&);
// class things
};
// output operator
template <std::size_t W, std::size_t H, std::size_t L>
std::ostream& operator<<(std::ostream&, const schematic<W,H,L>&);
// ...
#include "schematic_cpp.h"
#endif
schematic_cpp.h
// ...
// output operator
template <std::size_t W, std::size_t H, std::size_t L>
std::ostream& operator<<(std::ostream& lhs, const schematic<W,H,L>& rhs)
{
// lot of code involving external libraries and processing data from the object
}
// ...
我尝试过的事情
- 注释掉原理图.h 中的
operator<<声明 - 使
operator<<内联
【问题讨论】:
标签: c++ templates linker-errors