How to implement the factory method pattern in C++ correctly

后端 未结 11 1180
暗喜
暗喜 2020-11-22 14:55

There\'s this one thing in C++ which has been making me feel uncomfortable for quite a long time, because I honestly don\'t know how to do it, even though it sounds simple:<

11条回答
  •  春和景丽
    2020-11-22 15:28

    Have you thought about not using a factory at all, and instead making nice use of the type system? I can think of two different approaches which do this sort of thing:

    Option 1:

    struct linear {
        linear(float x, float y) : x_(x), y_(y){}
        float x_;
        float y_;
    };
    
    struct polar {
        polar(float angle, float magnitude) : angle_(angle),  magnitude_(magnitude) {}
        float angle_;
        float magnitude_;
    };
    
    
    struct Vec2 {
        explicit Vec2(const linear &l) { /* ... */ }
        explicit Vec2(const polar &p) { /* ... */ }
    };
    

    Which lets you write things like:

    Vec2 v(linear(1.0, 2.0));
    

    Option 2:

    you can use "tags" like the STL does with iterators and such. For example:

    struct linear_coord_tag linear_coord {}; // declare type and a global
    struct polar_coord_tag polar_coord {};
    
    struct Vec2 {
        Vec2(float x, float y, const linear_coord_tag &) { /* ... */ }
        Vec2(float angle, float magnitude, const polar_coord_tag &) { /* ... */ }
    };
    

    This second approach lets you write code which looks like this:

    Vec2 v(1.0, 2.0, linear_coord);
    

    which is also nice and expressive while allowing you to have unique prototypes for each constructor.

提交回复
热议问题