C++ 实现键为string、值为异构pair的std::unordered_map方案问询
你遇到的报错本质不是少了访问者模式,是两个基础逻辑问题:
- 拿到的是
Boundbase*基类指针,编译器根本不知道它实际指向的是Boundary<double>、Boundary<int>还是其他派生类,自然没法直接访问派生类才有的bpair成员 - 你代码里的
bpair是Boundary类的私有成员,哪怕你能拿到派生类指针,外部代码本来也没权限直接碰它
你现在的多态设计思路本身是对的,根本不需要推翻,也不用上复杂的访问者、第三方库,用原生STL就能简单解决。
第一步:给基类加通用虚接口
不用绕弯,既然你存基类指针就是为了不关心具体类型,那把所有通用操作(比如打印边界、序列化)做成基类的纯虚方法就行,比访问者简单数倍:
class Boundbase { public: Boundbase() = default; virtual ~Boundbase() = default; // 通用方法:把边界转成可直接打印的字符串,所有派生类必须实现 virtual std::string format_bound() const = 0; };
第二步:在派生类里实现接口,保持成员私有
把原来的Boundary模板类调整下,实现基类要求的接口,bpair还是保持私有,只通过类的方法暴露:
template <class dType> class Boundary : public Boundbase { std::pair<dType, dType> bpair; public: // 构造函数逻辑留着 Boundary(const std::string &lbound, const std::string &ubound) { setbound(lbound, ubound); } void setbound(const std::string &lbound, const std::string &ubound) { // 原来的字符串转值逻辑可以简化,不需要while循环 std::istringstream(lbound) >> bpair.first; std::istringstream(ubound) >> bpair.second; } std::pair<dType, dType> getbound() { return bpair; } // 实现基类要求的格式化方法 std::string format_bound() const override { std::ostringstream oss; oss << bpair.first << "," << bpair.second; return oss.str(); } };
这时候你main函数里原来的打印操作,直接调用基类的接口就行,根本不用管实际存的是什么类型:
auto sbound = tbounds.at("X1"); // 用at()比[]安全,key不存在直接抛错,不会偷偷插入空值 std::cout << sbound->format_bound() << std::endl;
第三步:需要取具体类型值时,加模板包装方法就行
如果你确实需要拿到具体的double/int/string边界值做运算(比如判断某个数是不是在边界范围内),根本不用硬写一堆dynamic_cast的分支,给Boundaries类加个模板查询方法就行:
class Boundaries { // 把原来的裸指针换成std::unique_ptr,自动管理内存,不会泄漏 std::unordered_map<std::string, std::unique_ptr<Boundbase>> bounds; public: // 模板方法:按指定类型查询边界 template <typename T> std::pair<T, T> get_specific_bound(const std::string& key) { auto* base_ptr = bounds.at(key).get(); // 安全做类型转换,转失败直接抛错 auto* derived_ptr = dynamic_cast<Boundary<T>*>(base_ptr); if (!derived_ptr) { throw std::runtime_error("查询的边界类型不匹配"); } return derived_ptr->getbound(); } // 原来的setboundmap逻辑调整下,存unique_ptr就行 void setboundmap(std::unordered_map<std::string, std::vector<std::string>> xtb) { for(auto& s : xtb) { char type = s.second[1][0]; switch(type) { case 'd': bounds[s.first] = std::make_unique<Boundary<double>>(s.second[2], s.second[3]); break; case 'i': bounds[s.first] = std::make_unique<Boundary<int>>(s.second[2], s.second[3]); break; case 'c': // 修正原来的字符串边界参数错误:之前左值右值都传了下界,这里补成正确的上界 bounds[s.first] = std::make_unique<Boundary<std::string>>(s.second[2], s.second[3]); break; } } } };
调用的时候写起来非常简洁:
// 要拿X1的double类型边界 auto d_bound = B.get_specific_bound<double>("X1"); // 要拿X2的string类型边界 auto str_bound = B.get_specific_bound<std::string>("X2");
这套方案的性能完全满足高频查询的需求——虚函数调用、dynamic_cast的开销都是纳秒级的,远低于你之前做字符串解析、文件读取的成本,不会成为性能瓶颈。
- 之前用裸指针
new出来的对象没有释放逻辑,会内存泄漏,换成std::unique_ptr自动管理,完全是STL原生能力 - 之前用
map[]访问不存在的key会偷偷插入空值,排查问题很麻烦,换成at()方法,key不存在会直接抛出异常,定位更快 - 之前
setbound里的while循环是冗余的,istringstream读一次值就结束,根本不会循环第二次
完全没必要。访问者适合的场景是“需要对不同派生类做十几种独立、稳定的操作,而且这些操作不会经常新增”。你现在的需求要么是通用的格式化操作(用虚接口就搞定),要么是按指定类型取值(用模板包装dynamic_cast就搞定),代码量比访问者少80%,新手也能看懂,性能和普通虚函数调用没有差别。
如果你后续想进一步简化,C++17自带的标准std::variant也能实现同样的效果,不需要额外引入第三方库,不过你现在的多态方案已经足够轻量,不需要硬换。
内容的提问来源于stack exchange,提问作者fatm

