我在C++中有一个模板化的容器类,它类似于std::map(它基本上是围绕std::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
是未处理的任意类类型的默认情况。有什么建议么? 最佳答案
您可以提供模板化的<<
运算符,以捕获未定义自定义输出运算符的情况,因为将首选任何更专业的版本。例如:
#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()
一样)。