gpt4 book ai didi

c++ - 如何为 operator<< 创建 C++ 模板

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:26:56 25 4
gpt4 key购买 nike

<分区>

在 C++ 中,我正在尝试编写 operator<< 的模板化版本对于 std::set这样我就不必为包含的值类型的每个排列编写一个。

我已将标题定义为 utils.h :

#ifndef UTILS
#define UTILS

#include <ostream>
#include <set>

template <typename T>
std::ostream &operator<<(std::ostream &os, const std::set<T> &tgt);

template <typename T>
inline std::ostream &operator<<(std::ostream &os,
const std::set<T> *tgt) {
return os << *tgt;
}

#endif

实现在 utils.cpp 中:

#include "utils.h"

template <typename T>
std::ostream &operator<<(std::ostream &os, const std::set<T> &tgt) {
os << "{";
bool first = true;
for (typename std::set<T>::const_iterator i = tgt.begin(); i != tgt.end();
i++) {
if (!first) {
os << ", ";
} else {
first = false;
}
os << i;
}
os << "}";
return os;
}

我尝试在 cout.cpp 中使用它:

#include <iostream>
#include <set>
#include "utils.h"

class Value {
public:
const int value;
Value(const int value) : value(value) {}
};

std::ostream &operator<<(std::ostream &os, const Value &tgt) {
os << "Value(" << tgt.value << ")";
return os;
}

inline std::ostream &operator<<(std::ostream &os, const Value *tgt) {
return os << *tgt;
}

int main(const int argc, const char **argv) {
std::cout << argc << std::endl;
std::cout << *argv << std::endl;
Value v(10);
std::cout << v << std::endl;
Value *w = &v;
std::cout << *w << std::endl;
std::set<const Value *> vs;
vs.insert(w);
vs.insert(&v);
Value x = Value(12);
vs.insert(&x);
std::cout << vs << std::endl;
std::set<const Value *> *p = &vs;
std::cout << p << std::endl;
return 0;
}

我正在尝试编译并运行它:

clang++ -c utils.cpp
clang++ -o cout cout.cpp utils.o
./cout

clang++ 的错误产生的是:

tmp/cout-6e3988.o: In function `main':
cout.cpp:(.text+0x24d): undefined reference to `std::ostream& operator<< <Value const*>(std::ostream&, std::set<Value const*, std::less<Value const*>, std::allocator<Value const*> > const&)'
/tmp/cout-6e3988.o: In function `std::ostream& operator<< <Value const*>(std::ostream&, std::set<Value const*, std::less<Value const*>, std::allocator<Value const*> > const*)':
cout.cpp:(.text._ZlsIPK5ValueERSoS3_PKSt3setIT_St4lessIS5_ESaIS5_EE[_ZlsIPK5ValueERSoS3_PKSt3setIT_St4lessIS5_ESaIS5_EE]+0x19): undefined reference to `std::ostream& operator<< <Value const*>(std::ostream&, std::set<Value const*, std::less<Value const*>, std::allocator<Value const*> > const&)'
clang: error: linker command failed with exit code 1 (use -v to see invocation)

我知道它没有找到合适的 operator<<链接期间的实现,但我不知道如何解决这个问题。

谢谢。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com