【发布时间】:2020-04-16 18:52:51
【问题描述】:
对于家庭作业,我必须使用非类型模板参数创建一个类,然后将std::(i/o)stream 运算符添加到它。但是,当我尝试编译 clang++ 时会出现链接器错误:
$ clang++ -o foo ./*.cpp -std=c++11 -Wall -Wextra -Wpedantic -Wconversion -Wnon-virtual-dtor
/tmp/16_15-8cda65.o: In function `main':
main.cpp:(.text+0x108): undefined reference to `operator<<(std::ostream&, Screen<9ul, 9ul> const&)'
clang: error: linker command failed with exit code 1 (use -v to see invocation)
我知道模板声明和定义必须在同一个翻译单元中,这里有很多问题和答案都指出了这一点。
我的删减代码如下:
main.cpp:
#include <iostream>
#include "Screen.h"
int main()
{
Screen<9,9> smile =
{
{0,0,0,1,1,1,0,0,0},
{0,1,1,0,0,0,1,1,0},
{0,1,0,0,0,0,0,1,0},
{1,0,0,1,0,1,0,0,1},
{1,0,0,0,0,0,0,0,1},
{1,0,1,0,0,0,1,0,1},
{0,1,0,1,1,1,0,1,0},
{0,1,1,0,0,0,1,1,0},
{0,0,0,1,1,1,0,0,0}
};
std::cout << smile;
return 0;
}
屏幕.h:
#ifndef SCREEN_H
#define SCREEN_H
#include <iostream>
#include <array>
#include <initializer_list>
#include <cstddef>
template <std::size_t W, std::size_t H>
class Screen
{
/////////////
// FRIENDS //
/////////////
friend std::ostream& operator<<(std::ostream&, const Screen<W,H>&);
public:
// declarations of ctors, public members, etc.
private:
//////////
// DATA //
//////////
std::array<std::array<bool,W>,H> pixels;
};
/////////////////
// NON-MEMBERS //
/////////////////
// ostream operator
template <std::size_t W, std::size_t H>
std::ostream& operator<<(std::ostream&, const Screen<W,H>&);
#include "Screen_impl.h"
#endif
Screen_impl.h:
#ifndef SCREEN_IMPL_H
#define SCREEN_IMPL_H
#include <iostream>
#include <array>
#include <algorithm>
#include <stdexcept>
#include <initializer_list>
#include <cstddef>
// definitions...
/////////////////
// NON-MEMBERS //
/////////////////
// ostream operator
template <std::size_t W, std::size_t H>
std::ostream& operator<<(std::ostream& lhs, const Screen<W,H>& rhs)
{
for (auto y = rhs.pixels.cbegin(); y < rhs.pixels.cend(); ++y)
{
for (auto x = y->cbegin(); x < y->cend(); ++x)
{
if (*x)
lhs << '#';
else
lhs << ' ';
}
lhs << std::endl;
}
return lhs;
}
#endif
【问题讨论】:
-
不太可能,因为我在这里没有看到明确的模板实例化。
-
@Michael 在
int main()之前插入template std::ostream& operator<<(std::ostream&, const Screen<9,9>&);会产生编译错误,表明该运算符不是Screen<9,9>的朋友
标签: c++ templates linker-errors friend-function