如何打印未知类型的对象 [英] How to print an object of unknown type

查看:106
本文介绍了如何打印未知类型的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a templatized container class in C++ which is similar to a std::map (it's basically a thread-safe wrapper around the std::map). I'd like to write a member function which dumps information about the entries in the map. Obviously, however, I don't know the type of the objects in the map or their keys. The goal is to be able to handle the basic types (integers, strings) and also some specific class types that I am particularly interested in. For any other class, I'd like to at least compile, and preferably do something somewhat intelligent, such as print the address of the object. My approach so far is similar to the following (please note, I didn't actually compile this or anything...):

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 和/或条目是未处理的任意类类型。任何建议?

This works for basic types. I can also write custom stream insertion functions to handle specific classes I'm interested in. However, I can't figure out a good way to handle the default case where Index and/or Entry is an unhandled arbitrary class type. Any suggestions?

推荐答案

您可以提供模板<< 运算符捕获没有定义自定义输出运算符的情况,因为任何更专门的版本将优先于它。例如:

You can provide a templated << operator to catch the cases where no custom output operator is defined, since any more specialized versions will be preferred over it. For example:

#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>

详情 命名空间是为了保持这个默认输出操作符不干扰在需要它的地方的代码。也就是说您应该只在 dumpKeys()方法中使用它(如中使用命名空间detail )。

The detail namespace is there to keep this "default" output operator from interfering with code in places other than where it is needed. I.e. you should only use it (as in using namespace detail) in your dumpKeys() method.

这篇关于如何打印未知类型的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆