2014-02-17 59 views
7

我一直在閱讀基於概念的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

我沒有在那裏看到什麼概念。這只是普通的基於類的多態(不管這個名稱是什麼)。 (編輯:哦,現在我看到它是如何工作的......這個評論可能完全錯誤) – immibis

+0

注意:C++程序員通過C++ 0x建議強烈關聯「Concepts」,用於檢查作爲支持的模板參數傳遞的類型語義;這個問題是關於「基於概念的多態性」,它是使用編譯時多態來創建運行時多態對象的獨特習慣。 –

+0

是的這就是我正在談論的Tony D. Keen的評論。 –

回答

2

的幾點:

  • 我看不出有什麼好的理由把drawable_conceptdrawable_modelgraphics_surface - 你只是防止東西是在其他容器類型可能有用的重用......

  • 你有一些const問題

    • draw大概應該是const(和函數定義不應該跟着分號;-)

    • drawable_model(T& item)應採取item通過const參考

    • push_back(T& drawable) shoudl通過const參考

  • 採取drawable你應該使用make_shared作爲例外安全

  • 「工廠」功能將無疑會更好分離到一個單獨的功能,而不是埋內push_back

+0

好點。你認爲這是基於概念的多態性的合理實現嗎? –

+0

@BlairDavidson:其基本功能在那裏......其餘的部分將適合您的實際使用,並且應該在洗滌中出來。有值得注意的變化 - 例如,創建運行時多態對象只包含指向具體類型的指針,而不是讓包裝器擁有具體對象,並且必須分配堆。無論您是否試圖最小化數據複製(例如,對共享內存中對象的併發運行時多態訪問與指針/包裝器一起工作),最優選取決於相對生命週期。 –

+0

這個問題是專門談論肖恩家長的工作:[基於概念的運行時多態性](http://stlab.adobe.com/wiki/images/c/c9/Boost_poly.pdf)。該示例使用私人概念和模型類,但它並未明確涵蓋該選擇的動機。 – bames53

-2

trianglesquare類應該從graphics_surface::drawable_concept繼承。閱讀關於virtual method tables

另請參閱wikipage Concepts in C++

+2

這不就是基於概念的多態嗎? –

1

這裏的方法更多的是關於類型擦除而不是基於概念的編程。它是boost :: any使用的思想的擴展。概念是類或函數模板所需類型的一組約束。 STL具有諸如ForwardIterator和InputIterator之類的概念。例如,這些約束對於傳遞給某些std算法的參數預計會成立。

+1

不幸的是,根據您的答案和延遲/殺死(?)C++ 0x提議的「概念」與一些人所稱的「基於概念的多態性」完全不同 - 用於捕獲任意類型的特定操作的模板工廠 - 這就是問題所在。 –

+0

嗯。是的,我同意你對我答案的評估。 –