对相同标题文件中定义的模板运算符的未定义引用

问题描述 投票:0回答:1

尝试使用我编写的模板化运算符时,我从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;
}

schematic.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
1个回答
0
投票

您的类是模板,但不是朋友功能声明,请尝试添加如下内容:

  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..
© www.soinside.com 2019 - 2024. All rights reserved.