I am a Java user trying my hand at c++.
In the below legacy code, I have multiple derived classes.
The contents of the map in each derived class are similar differing by just a few.
The function pr() is repetitive.
I would like to optimize such piece of code.
Do let me know ideas/suggestions?
Thanks
#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>());
}