c++ - 如何优化 C++ 遗留样板代码?
问题描述
我是一名 Java 用户,正在尝试使用 c++。
在下面的遗留代码中,我有多个派生类。
每个派生类中映射的内容都是相似的,只是略有不同。
函数 pr() 是重复的。
我想优化这样的代码。
让我知道想法/建议吗?
谢谢
#include <iostream>
#include <map>
#include <string>
#include <functional>
using namespace std;
#include <memory>
class X {
public:
virtual void pr ()=0;
};
class Y: public X {
std::map<string,int> fm{ {"mem1", 33},
{"mem2", 44},
{"YYY", 999}};
public:
virtual void pr () {
for(auto const &[k,v] : fm)
{
std::cout<<k <<" : "<<v <<std::endl;
}
}
};
class Z: public X {
sstd::map<string,int> fm{ {"mem1", 33},
{"mem2", 44},
{"ZZZ", 777}};
public:
virtual void pr () {
for(auto const &[k,v] : fm)
{
std::cout<<k <<" : "<<v <<std::endl;
}
}
};
void fn(std::unique_ptr<X> x)
{
x->pr();
}
int main()
{
fn(std::make_unique<Y>());
}
解决方案
我会放弃派生类,你只有在构造上有所不同。
#include <map>
#include <string>
#include <utility>
class X {
std::map<string,int> fm;
public:
X(std::map<string,int> fm): fm(std::move(fm)) {}
void pr () {
for(auto const &[k,v] : fm)
{
std::cout<<k <<" : "<<v <<std::endl;
}
}
};
X Y(){ return X({ {"mem1", 33}, {"mem2", 44}, {"YYY", 999}}); }
X Z(){ return X({ {"mem1", 33}, {"mem2", 44}, {"ZZZ", 777}}); }
int main()
{
Y().pr();
}
推荐阅读
- ruby - 根据 URL 更改 CSS
- css - 更改同名类的 CSS
- mysql - 通过私有 IP 拒绝 Google Cloud MySQL 访问,但允许通过公共 IP 访问
- android-glide - 滑翔不会触发任何结果并卡住加载
- amazon-ec2 - 如何确定为什么在下载文件时在 EC2 实例上杀死 Python 进程?
- angular - 角度 8 下拉更改事件不起作用
- python - 使用 seaborn.FacetGrid 时如何更改 X 轴上分类值的顺序?
- java - 为什么我的 Java 8 流在 Maven 插件中不起作用?
- c# - 在提交表单之前捕获输入类型“月”的值
- spring-security - HttpServletRequest 在经过身份验证的 IDP 并重定向到 SP 后返回空会话