首页 > 解决方案 > 如何优化 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>());
}

标签: c++

解决方案


我会放弃派生类,你只有在构造上有所不同。

#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();
}

推荐阅读