【发布时间】:2017-11-02 20:42:18
【问题描述】:
我正在 c++11 中尝试多态性和 boost::variant
这里是代码
#include <iostream>
#include <boost/variant.hpp>
using namespace std;
class Polygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{
width=a;
height=b;
}
};
class Rectangle: public Polygon {
public:
Rectangle() {
std::cout << "ctor rectangle" << std::endl;
}
int area()
{
return width*height;
}
};
class Triangle: public Polygon {
public:
Triangle() {
std::cout << "ctor triangle" << std::endl;
}
int area()
{
return width*height/2;
}
};
int main () {
Triangle r;
boost::variant<Rectangle, Triangle> container = r;
int x = 4;
int y = 5;
if (container.type() == typeid(Rectangle)) {
r.set_values(x,y);
std::cout << r.area() << std::endl;
} else if ( container.type() == typeid(Triangle)){
r.set_values(x,y);
std::cout << r.area() << std::endl;
}
return 0;
}
我想知道这是否是最好的方法。代码中有重复(在 main() 函数中),对于每种类型(我们在运行时获取类型)我们执行相同的操作,即设置值并打印区域。
有没有更好的方法来做到这一点?
【问题讨论】:
-
为什么不在
Polygon中添加virtual int area()?我认为这里不需要variant;在这个例子中,正则多态可以正常工作。 -
另外,RTTI 通常是一个坏主意,在使用
variant时应该是不必要的。您想改用访问者。 -
如果问题是“如何消除代码中的重复”,这个问题似乎很好。但是您的最后陈述说“有没有更好的方法来做到这一点?”,这太宽泛/不清楚了。如果您的意思是“我如何调用
boost::variant的方法”,那也很好(不包括骗子)。明确你的问题 -
C++14 让这变得更好。你被 C++11 困住了吗?
标签: c++ c++11 boost boost-variant