【发布时间】:2021-03-02 20:57:33
【问题描述】:
我有一个包含 std::map 的类,我在下面对其进行了简化。我想实现一个 to_string() 函数,它将第一个和第二个映射条目通过运算符<< 流式传输到字符串流中 - 然后返回字符串结果。
这适用于 int、float、string 等...基本上可以流式传输的任何内容。
但是enum class xzy : int {...}; 不能是流式的——或者它必须首先是 static_cast。但是在我的模板中,如果我将 static_cast 放在 x.second 周围,那么它将破坏其他模板类型。
我想知道如何处理这个问题。我的第一个想法是尝试使用类型特征来检测类型是否是整数(然后对其进行静态转换),否则只依赖普通的operator << 函数。
这里是类:
template<typename T1, typename T2>
class map_wrapper
{
public:
std::map<T1, T2> m_map;
std::map<T1, T2> &map() {return m_map;}
std::string to_string()
{
std::stringstream ss;
for (const auto &item : m_map)
{
// <----------------------- ISSUE HERE
// So I want this to handle as many types as possible
// Maybe I can do some sort of if type traits == integral then static cast?
ss << item.first << ", " << static_cast<int>(item.second) << "\n";
//ss << item.first << ", " << item.second << "\n";
}
return ss.str();
}
};
这是我的测试代码:
enum class types : int
{
type1,
type2,
type3
};
int main()
{
// This is all ok
map_wrapper<int, int> int_map;
int_map.map() = {{1, 2}, {3, 4}};
std::cout << int_map.to_string() << std::endl;
// This only works if I static_cast the enum types to an int within to_string()
map_wrapper<int, types> type_map;
type_map.map() = {{1, types::type1}, {2, types::type2}};
std::cout << type_map.to_string() << std::endl;
return 0;
}
我已经注释了不能按我想要的那样工作的部分。
实时可编辑示例:https://godbolt.org/z/rh8Y5v
更新
注意类型枚举只是一个示例 - 我希望它可以理想地与任何枚举类一起使用
【问题讨论】:
标签: c++ templates typetraits