基于概念的多态性
Concept Based Polymorphism
我一直在阅读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
- 您只是阻止重用在其他容器类型中可能有用的东西...... -
您有一些
const
问题-
draw
可能应该const
(函数定义后面不应该跟分号;-) -
drawable_model(T& item)
应通过const
参考item
-
push_back(T& drawable)
应通过const
参考drawable
-
-
您应该使用
make_shared
以确保异常安全 -
"工厂"功能可以说最好分离成一个单独的功能,而不是埋在
push_back
你在这里的方法更多的是关于类型擦除,而不是关于基于概念的编程。它是boost::any使用的想法的扩展。概念是对类或函数模板所需类型的一组约束。STL具有ForwardIterator和InputIterator等概念。例如,对于传递给某些 std 算法的参数,这些约束应该是正确的。
相关文章:
- 多态性和功能结合
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- C++boost序列化多态性问题
- 如何查找哪个类对象位于数组的特定索引上(多态性)
- 如何在多线程中正确使用unique_ptr进行多态性?
- 具有智能指针的多态性
- 在 C++ 中在堆栈上创建实例时如何保持多态性?
- 继承/多态性 - 我是否被迫使用"protected"变量?
- C++ 多态性在代码::块 17.12 中不起作用
- C++ 泛型和多态性:这种模式可行吗?
- 为什么我们实际上需要运行时多态性?
- 如何在这个简单的最小示例中实现多态性?
- 考虑 .(点)应用于应该是运行时多态性的东西时
- 如何使用多态性将相同的操作应用于具有相同基类的不同对象的unordered_sets
- 在C++中使用多态性相对于继承的实际优势
- 基于概念的多态性
- C++ 多态性概念
- C++等价于简单的Java多态性
- 多态性概念