c – 基于概念的多态性

我一直在阅读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_concept或drawable_model放在graphics_surface中 – 你只是防止重用在其他容器类型中可能有用的东西……
>你有一些常见问题

> draw应该是const(函数定义不应该用分号;-)
> drawable_model(T& item)应该通过const引用获取项目
> push_back(T& drawable)shoudl通过const引用获取drawable

>你应该使用make_shared来保护异常安全>“工厂”功能可以说是更好的分离成一个单独的功能,而不是埋没在push_back中

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...