c++ - 基于概念的多态性

标签 c++ polymorphism duck-typing

我一直在阅读 C++ 中基于概念的继承。我附上了所有代码示例。我基本上是在问这是否是这个概念的正确实现?我对此很陌生,所以我只是记下我的想法。欢迎任何评论/批评。

#include "stdafx.h"
#include <memory>
#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

struct Point{
    int x;
    int y;
};

class graphics_surface{

    class drawable_concept{
    public:
        virtual void draw(Point const& coordinate) {};
        virtual ~drawable_concept() {};
    };

    template<class T>
    class drawable_model : public drawable_concept{
    public:
        drawable_model(T& item) : item_(item){}
        void draw(Point const& coordinate){
            item_.draw(coordinate);
        }
        ~drawable_model(){}
    private:
        T item_;
    };

public:

    template<class T>
    void push_back(T& drawable){
        v_.push_back(shared_ptr<drawable_concept>( new drawable_model<T>(drawable)));
    }

    void draw(Point const& coordinate) {
        for_each(v_.begin(), v_.end(), [&](shared_ptr<drawable_concept>& concept){
            concept->draw(coordinate);
        });
    }

private:
    vector<shared_ptr<drawable_concept>> v_;
};

struct triangle{
    void draw(Point const& p){
        cout << "Triangle: " << p.x << "," << p.y << endl;
    }
};

struct square{
    void draw(Point const& p){
        cout << "Sqaure: " << p.x << "," << p.y << endl;
    }
};


int _tmain(int argc, _TCHAR* argv[])
{

    Point p;
    p.x = 1;
    p.y = 2;

    graphics_surface surface;
    surface.push_back(triangle());

    surface.draw(p);

    return 0;
}

提前致谢。

布莱尔

最佳答案

几点:

  • 我看不出有什么好的理由将 drawable_conceptdrawable_model 放在 graphics_surface 中 - 你只是防止重复使用某些东西可能在其他容器类型中有用...

  • 你有一些const问题

    • draw 可能应该是 const(并且函数定义后面不应跟分号 ;-)

    • drawable_model(T& item) 应该通过const 引用获取item

    • push_back(T& drawable) 应该通过const 引用drawable

  • 为了异常安全,您应该使用make_shared

  • “工厂”功能最好分离成一个单独的函数,而不是埋在 push_back

关于c++ - 基于概念的多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21821948/

相关文章:

c++ - 包含 Map(具有对象值)和 Multimap(具有 std::string 值)的对象的 boost 序列化:需要什么?

java - Java中的多态方法返回类型向下转换

c++ - 多态时识别对象的类型

C++虚拟析构函数导致调用基方法

c# - C#和Java是鸭子类型(duck typing)的吗?

c++ - 无法使用 Yocto 为 Windows 生成 SDK

c++ - 引用成员变量作为类成员

C++ Primer(第5版)初学者的困惑

java - 为什么必须在 Java 中声明接口(interface)?

java - println(String) 接口(interface)