尝试使用我编写的模板化运算符时,我从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中所述。由于它仍然给我链接器错误,所以我在这里询问。
// 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;
}
#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
// ...
// 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
}
// ...
operator<<
声明operator<<
内联您的类是模板,但不是朋友功能声明,请尝试添加如下内容:
template <std::size_t W, std::size_t H, std::size_t L>
class schematic {
template <std::size_t X, std::size_t Y, std::size_t Z>
friend std::ostream& operator<<(std::ostream&, const schematic<W, H, L>&);
// rest code..