C++私有(private)多态实现设计

标签 c++ c++11 polymorphism

这是一个 C++(11) 问题。 我有一个对象Obj myObj封装对象 f类型 MyType . 根据运行时上下文,对象 f应该表现不同。

一个自然的实现方式是类 Obj封装指向抽象基类的指针 MyType , 这将根据上下文指向 MyType 的不同(公共(public))子级,例如 MyType1 , MyType2

不过,我不太喜欢Obj “遭受”MyType的后果是多态的,即必须处理一个指针。特别是,如果我将它设为 std::unique_ptr<MyType> , 这意味着 Obj要么不能被复制,要么需要给它一个适当的复制构造函数来处理复制 MyType 资源。

在我看来,MyType多态不应该是Obj的问题。

我参加了以下类(class)。本质上,这个想法是将指针隐藏在 MyType 中。私有(private)属性。此外,我的第二个问题涉及到 MyTypeImpl 的具体实现。可能会共享一些代码不应该重复。我把它放在一个具体实现私有(private)继承的类中。

我很好奇比我更专业的开发人员会怎么想。 “只是为了隐藏指针”太重了吗?有更好的方法吗?

#include <iostream>
#include <memory>


// a "standard" implementation of MyType
class MyTypeImpl
{
    public:        
        virtual double operator()(double a) = 0;
        virtual int implType() const = 0;
        virtual void complexStuff() const = 0;
};



// some internal stuff common to all implementations
class MyTypeImplInternals
{
protected:    
    MyTypeImplInternals(int value):factor_{value}{}
    int factor_;
    void longCommonFunction() const{ std::cout << "I'm doing complex stuff common to all interfaces " << factor_ << "\n" ;}
};


// one specific implementation
class MyTypeImpl1: public MyTypeImpl, private MyTypeImplInternals
{
    public:
        MyTypeImpl1(int factor):MyTypeImplInternals{factor}{};

        virtual double operator()(double a) override {return factor_*a;} 
        virtual int implType() const override {return 1;}
        virtual void complexStuff() const override { longCommonFunction(); }
};


// a second implementation
class MyTypeImpl2: public MyTypeImpl, private MyTypeImplInternals
{
    public:
        MyTypeImpl2(int factor):MyTypeImplInternals{factor}{};
        virtual double operator()(double a) override {return factor_*a;} 
        virtual int implType() const override {return 2;}
        virtual void complexStuff() const override { longCommonFunction(); }
};



class MyTypeImplFactory
{
    public:
    static std::unique_ptr<MyTypeImpl>createMyTypeImpl(int implementationType)
    {        
        switch(implementationType)
        {
            case 1:            
              return std::unique_ptr<MyTypeImpl> (new MyTypeImpl1(12));

             case 2:
                return std::unique_ptr<MyTypeImpl> (new MyTypeImpl2(22));

            default:
                throw std::runtime_error("implementation does not exist...\n");
                return nullptr;
        }
    }
};



// my type
class MyType
{
    public:

        MyType(int implementationType)
        {
            implPtr_ = MyTypeImplFactory::createMyTypeImpl(implementationType);   
        }

        MyType(MyType const& source)
        : implPtr_{ MyTypeImplFactory::createMyTypeImpl(source.implType()) }
        {
        }


        double operator()(double a){return (*implPtr_)(a);}  
        int implType() const {return implPtr_->implType();}
        void complexStuff() const {implPtr_->complexStuff();}


    private:
        std::unique_ptr<MyTypeImpl> implPtr_;
};








class Obj
{
 private:
    MyType f;

public:
    Obj(int dim):f{dim}{}    
    Obj(Obj&& sourceToMove) = default;
    Obj(Obj const& source) = default;

    void doStuff() {std::cout << "I'm doing stuff()  " << f(2) << std::endl; f.complexStuff();}
};







int main()
{
 Obj myObj{1}, myObj2{2};

 myObj.doStuff();
 myObj2.doStuff();

 Obj myObj3{std::move(myObj2)}; // myObj2 now dead
 Obj myObj4{myObj}; 

 myObj3.doStuff();
 myObj4.doStuff();

}

在线编译器链接:http://cpp.sh/8rhyy

这里的实现非常愚蠢,可以作为示例。此设计的应用程序可以是例如 Solver ( Obj ) 解决了某种物理问题 Equation ( MyType ) 具体定义取决于问题的维数,1D 空间中的方程与 2D 或 3D 中的方程不同。 Solver的代码将完全独立于 Equation的维度,也不必处理指针。 Equation会对外界隐藏其 1D、2D 或 3D 实现。

(最初是 code review 上的帖子,由于要抽象而被搁置)

最佳答案

这个提议的类设计似乎有一个明显的问题。多态类型由 std::unique_ptr 引用:

std::unique_ptr<MyTypeImpl> implPtr_;

Obj 的默认复制构造函数和赋值运算符最终会将持有的指针转移到新对象,而原始对象中的 std::unique_ptrnullptr 处。不好。

至少这应该是 std::shared_ptr,或者 Obj 的复制构造函数和赋值运算符需要实例化一个新的 implPtr_ 。请注意,使用简单的 std::shared_ptr 修复复制构造函数的结果,并且赋值运算符有多个 Obj 实例引用相同的 MyTypeImpl,这可能是也可能不是问题。

一个更简单的类设计就是让 MyTypeImpl1MyTypeImpl2 成为 Obj 的子类,实现所需的多态行为。

关于C++私有(private)多态实现设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39190729/

相关文章:

c++ - 使用虚拟继承的未对齐地址

c++ - 类型特征以匹配指向集合的指针

c++ - 如何提取__VA_ARGS__?

C函数修饰/多态

c++ - std::map 的顺序

C++ CALLBACK函数类型

c++ - 如何复制文件的二进制数据

c++ - 在类成员函数中获取引用并将其分配给 C++ 中的类数据成员(引用)

haskell - 你在 Haskell 中发现了更高级别的类型有什么用途?

Linq 对不同类型的列表进行排序