簡體   English   中英

如何聲明從 EnumType 到 EnumTypeValue 的 std::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 CARParkingSlotContainer<CAR>BIKEParkingSlotContainer<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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM