gpt4 book ai didi

c++ - 如何打印未知类型的对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:50:16 25 4
gpt4 key购买 nike

我有一个用 C++ 编写的模板化容器类,它类似于 std::map(它基本上是 std::map 的线程安全包装器)。我想编写一个成员函数来转储有关 map 中条目的信息。但是,显然,我不知道 map 中对象的类型或它们的键。目标是能够处理基本类型(整数、字符串)以及我特别感兴趣的一些特定类类型。对于任何其他类,我想至少编译,最好做一些有点智能的事情,比如打印对象的地址。到目前为止,我的方法类似于以下内容(请注意,我实际上并没有编译这个或任何东西......):

template<typename Index, typename Entry>
class ThreadSafeMap
{
std::map<Index, Entry> storageMap;
...
dumpKeys()
{
for(std::map<Index, Entry>::iterator it = storageMap.begin();
it != storageMap.end();
++it)
{
std::cout << it->first << " => " << it->second << endl;
}
}
...
}

这适用于基本类型。我还可以编写自定义流插入函数来处理我感兴趣的特定类。但是,我想不出一个好的方法来处理 Index 和/或 Entry 的默认情况 是未处理的任意类类型。有什么建议吗?

最佳答案

您可以提供一个模板化的 << operator 来捕获未定义自定义输出运算符的情况,因为任何更专业的版本都将优先于它。例如:

#include <iostream>

namespace detail
{
template<typename T, typename CharT, typename Traits>
std::basic_ostream<CharT, Traits> &
operator<<(std::basic_ostream<CharT, Traits> &os, const T &)
{
const char s[] = "<unknown-type>";
os.write(s, sizeof(s));
return os;
}
}

struct Foo {};

int main()
{
using namespace detail;
std::cout << 2 << "\n" << Foo() << std::endl;
return 0;
}

将输出:

2
<unknown-type>

detail namespace是否可以防止此“默认”输出运算符在需要的地方以外的地方干扰代码。 IE。你应该只在你的 using namespace detail 中使用它(如 dumpKeys() )方法。

关于c++ - 如何打印未知类型的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3312486/

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