【发布时间】:2022-01-23 12:41:46
【问题描述】:
我有一个有效的例子: 我为枚举的每个值创建一个实现“PartInterface”的对象,并将它们添加到映射中。但我觉得这并不令人满意,因为一切都可以在编译时而不是在运行时推断出来。 在 c++ 11 中有没有更优雅的方法来做到这一点? 另一种解决方案是在每次调用“get”函数时构建“YearPart”、“MonthPart”和“DayPart”对象, 但在我看来效率较低......
#include <iostream>
#include <map>
#include <memory>
struct Date{
int year;
int month;
int day;
};
class PartInterface{
public:
virtual const std::string & getName()const=0;
virtual int getValue(const Date& d)const=0;
virtual ~PartInterface(){}
};
class Part : public PartInterface{
public:
Part(const std::string& name):_name(name){}
const std::string & getName()const{
return _name;
}
virtual int getValue(const Date& d)const=0;
private:
std::string _name;
};
class YearPart : public Part{
public:
YearPart():Part("year"){}
int getValue(const Date& d)const{
return d.year;
}
};
class MonthPart : public Part{
public:
MonthPart():Part("month"){}
int getValue(const Date& d)const{
return d.month;
}
};
class DayPart : public Part{
public:
DayPart():Part("day"){}
int getValue(const Date& d)const{
return d.day;
}
};
enum DatePart{
Year,
Month,
Day
};
class Parts{
public:
Parts(){
_map[Year].reset(new YearPart());
_map[Month].reset(new MonthPart());
_map[Day].reset(new DayPart());
};
const PartInterface& get(const DatePart& date_part)const{
return * (_map.find(date_part)->second);
}
private:
std::map<DatePart, std::unique_ptr<PartInterface> > _map;
};
int main() {
Date d({2016, 7, 23});
const Parts parts;
std::cout << "Date "
<< parts.get(Year).getValue(d) << " "
<< parts.get(Month).getValue(d) << " "
<< parts.get(Day).getValue(d) << std::endl;
return 0;
}
【问题讨论】:
-
为什么要建立自己的日期库?那只是自找麻烦……
-
@Dai,这只是为了创建一个有意义的例子,但我经常遇到这个设计问题。
-
tbh,整个设计相当有问题,不仅仅是从枚举到派生类实例的运行时映射。为什么首先使用派生类?为什么
getValue不是static或免费功能? -
@463035818_is_not_a_number 这个想法是创建将枚举作为参数的 getValue 和 getName 函数?确实,这似乎是一个很好的解决方案,但是我喜欢使用类将同一“部分”的所有元素组合在一起的想法。
-
你为什么用
std::map::find,如果你不测试,结果有没有?如果有人传入Day+1,对函数结果的任何访问都会产生未定义的行为。此外,考虑到开销,为什么要使用std::map?枚举常量具有整数值 0、1 和 2,那么为什么不将_map声明为std::unique_ptr<PartInterface>[3]?
标签: c++ dictionary c++11 enums constants