![](/img/trans.png)
[英]How do I declare an iterator for a map with the following template - std::map<std::string, T> my_map?
[英]How to declare a std::map from EnumType to EnumTypeValue?
我有一個枚舉:
enum VehicleType {CAR, BIKE, TRUCK};
以下 class 使用此枚舉作為模板參數:
template <VehicleType V>
class ParkingSlotContainer
{
...
};
現在,我希望定義一個 class 和一個 map 數據成員,將VehicleType
映射到ParkingSlotContainer<VehicleType>
。 換句話說,我想要 map CAR
到ParkingSlotContainer<CAR>
, BIKE
到ParkingSlotContainer<BIKE>
等。
這是我的嘗試:
class ParkingFloor
{
private:
int floor;
map<VehicleType, ParkingSlotContainer<VehicleType> > slots;
public:
ParkingFloor(...);
...
};
編譯器不接受上述內容並報告type name is not allowed
。 它需要ParkingSlotContainer<CAR|BIKE|TRUCK>
而不是ParkingSlotContainer<VehicleType>
。
定義這樣一個 map 的正確方法是什么?
問題是您不能在std::map
中擁有兩個不同類型的值:例如,您不能在slots
變量中同時擁有ParkingSlotContainer<BIKE>
和ParkingSlotContainer<CAR>
,因為它們是不同的類型。
對於這些您想從枚舉值生成類型的情況,您可能需要使用更高階的宏。 這是一個應用於您的代碼的高階宏的示例,我們使用它們為三個枚舉值聲明三個成員變量( _CAR
、 _BIKE
和_TRUCK
),然后生成重載方法setSlot
以將新值設置為其中任何一個. 只是為了演示如何使用高階宏:
#define FOREACH_VEHICLE_TYPE(OP) \
OP(CAR) \
OP(BIKE) \
OP(TRUCK)
enum VehicleType {
#define DECL_VEHICLE(name) name,
FOREACH_VEHICLE_TYPE(DECL_VEHICLE)
#undef DECL_VEHICLE
};
template <VehicleType V>
class ParkingSlotContainer
{
public:
int vehicleCount = 0;
};
class ParkingFloor
{
private:
int floor;
#define DECL_SLOT(name) ParkingSlotContainer<name> _##name;
FOREACH_VEHICLE_TYPE(DECL_SLOT)
#undef DECL_SLOT
public:
#define SET_SLOT(name) void setSlot(const ParkingSlotContainer<name>& newValue) {_##name = newValue;}
FOREACH_VEHICLE_TYPE(SET_SLOT)
#undef SET_SLOT
};
int main() {
ParkingSlotContainer<BIKE> bikes;
bikes.vehicleCount = 119;
ParkingFloor parkingFloor;
parkingFloor.setSlot(bikes);
return 0;
}
根據您的應用程序,這可能會或可能不會矯枉過正。 這有點讓代碼更難閱讀......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.