基于概念的多态性

时间:2014-02-17 06:08:42

标签: 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;
}

提前致谢。

布莱尔

3 个答案:

答案 0 :(得分:2)

几点:

  • 我认为没有任何理由将drawable_conceptdrawable_model置于graphics_surface内 - 您只是阻止重复使用其他容器类型中可能有用的内容......

  • 您有一些const个问题

    • draw应该是const(函数定义不应该以分号跟随; - )

    • drawable_model(T& item)item const参考

    • push_back(T& drawable)通过drawable参考提取const

  • 您应该使用make_shared进行例外安全

  • “工厂”功能最好分成单独的功能,而不是埋没在push_back

答案 1 :(得分:1)

这里的方法更多是关于类型擦除而不是基于概念的编程。它是boost :: any使用的思想的延伸。概念是类或函数模板所需类型的一组约束。 STL具有ForwardIterator和InputIterator等概念。例如,对于传递给某些std算法的参数,这些约束是预期的。

答案 2 :(得分:-3)

您的trianglesquare类应继承自graphics_surface::drawable_concept。阅读virtual method tables

另见Concepts in C++上的wikipage。

相关问题