多态二进制函数
Polymorphic binary function
我有三个形状类Circle
、Square
、ConvexPolygon
,并且我有函数
bool ShapesIntersect(const Circle& s1, const Circle& s2);
bool ShapesIntersect(const Circle& s1, const Square& s2);
// ... and the other 7 combinations
我想要一个类似的多态函数
Matrix<bool> ComputeShapeIntersectionMatrix(
const vector<Shape>& shapes1,
const vector<Shape>& shapes2);
调用上面特定于形状的方法来填充相交矩阵。
我认为在c++中不可能做到这一点,但我可以接受任何其他解决方案,只要我可以在不更改计算交集矩阵的代码的情况下添加新的形状类型。
我做了一个多调度器。
如果使用std::variant
,它会变得更简单:
using Shape = std::variant<Circle, Square, ConvexPolygon>;
struct intersect
{
template <typename Shape1, typename Shape2>
bool operator()(const Shape1& lhs, const Shape2& rhs) const {
return ShapesIntersect(lhs, rhs);
}
};
Matrix<bool> ComputeShapeIntersectionMatrix(
const vector<Shape>& shapes1,
const vector<Shape>& shapes2)
{
Matrix<bool> res(shapes1.size(), shapes2.size());
for (std::size_t i = 0; i != shapes1.size(); ++i) {
for (std::size_t j = 0; j != shapes2.size(); ++j) {
res[i][j] = std::visit(intersect{}, shapes1[i], shapes2[j]);
}
}
return res;
}
我会这样解决它:
struct Circle;
struct Polygon;
struct Square;
struct Intersector {
virtual bool intersects(const Circle& ) const = 0;
virtual bool intersects(const Polygon& ) const = 0;
virtual bool intersects(const Square& ) const = 0;
};
template<class SHAPE>
struct ShapeIntersetor;
template<>
struct ShapeIntersetor<Square> : Intersector {
const Square& square;
ShapeIntersetor(const Square& square) : square(square) { }
bool intersects(const Circle& ) const override { /* Intersection code */ }
bool intersects(const Polygon& ) const override { /* Intersection code */ }
bool intersects(const Square& ) const override { /* Intersection code */ }
};
// Repeat above for each shape type
struct Shape {
virtual ~Shape() = default;
virtual std::unique_ptr<Intersector> get_intersector() const = 0;
virtual bool intersects(const Intersector& isector) const = 0;
};
struct Polygon : Shape {
std::unique_ptr<Intersector> get_intersector() const override {
return make_unique<ShapeIntersector<Polygon>>(*this);
}
bool intersects(const Intersector& isector) const override {
return isector.intersects(*this);
}
};
// Repeat above for each shape type
相关文章:
- 多态二进制函数
- 二进制搜索树没有匹配的函数调用
- 为二进制树编码remove()函数
- 如何使用 BOOST 二进制函数概念?
- 在Qt中使用C++Lambda函数作为插槽是否有助于保持库的二进制兼容性?
- 模板函数中的无捕获 lambda 是否具有多个二进制实现?
- 如何将Z3_ast导出为二进制以及如何搜索函数名称?
- 查找二进制文件的大小,函数 tellg() 返回 -1
- 类型长的长度和未解决的超载函数类型的类型的操作数与二进制运算符
- 类没有合适的复制构造函数,找不到二进制运算符 '=',
- Rcpp - 用二进制函数转换数字向量?
- 没有变量声明为函数,但错误:二进制表达式的操作数无效
- 为什么新的虚拟函数不会破坏二进制兼容性的现象?
- C++中的类/函数模板占用了我的二进制文件的百分比是多少?
- 错误:二进制表达式的操作数无效(映射使用查找函数错误)
- <未解析的重载函数类型>调用二进制谓词
- 此TreeVisitor函数如何用于此二进制搜索树分配
- 在 C++ 中使用按位运算符理解十进制到二进制函数的问题
- 使用二进制检测挂钩函数
- 从构造函数二进制中删除"显式"是否兼容?