简体   繁体   中英

How to return different types of variable from switch statement in c++

I am trying to implement factory to return instance of derived class based on passed class id.

    class Day : public IDay {
        /* ... */
    };

    class Day01 : public Day {
        void calculate_part1() override;
        /* ... */
    };
    .
    .
    .
    class Day25 : public Day {
        void calculate_part1() override;
        /* ... */
    };



    std::unique_ptr<Day> Factory::createDay(uint8_t id) {

        //how to extract "day" variable from switch and pass it to return statement?

        switch (id) {
            case 1: { Day01 day{}; break; } 
            case 2: { Day02 day{}; break; }
            ....
            case 25:{ Day25 day{}; break; }
            default:{ Day day{}; }
        }

        return std::make_unique<decltype(day)>(id, info[id].name, info[id].url,
                                     info[id].input_data_file);
    }

Day01...Day25 are classes with unique calculate function.

I have tried to create Day day{} variable in class scope before switch and then downcast it to Day01... with dynamic_cast inside switch . In that case I have lost unique calculate functions in derived classes. I probably can achieve that with help of templates but will appreciate any help to get it done without it.

You need a different instantiation of make_unique for each derived type. So you end up needing code like:

std::unique_ptr<Day> Factory::createDay(uint8_t id) {
    switch (id) {
        case 1: return std::make_unique<Day01>(id, info[id].name, info[id].url,
                                 info[id].input_data_file);
        case 2: return std::make_unique<Day02>(id, info[id].name, info[id].url,
                                 info[id].input_data_file);
        case 3: return std::make_unique<Day03>(id, info[id].name, info[id].url,
                                 info[id].input_data_file);
            :

If your concern is to reduce repetitive typing, you could wrap the make_unique call in another template:

template<class DAY, uint8_t ID> std::unique_ptr<Day> Factory::createDay() {
    return std::make_unique<DAY>(ID, info[ID].name, info[ID].url,
                                   info[ID].input_data_file); }

std::unique_ptr<Day> Factory::createDay(uint8_t id) {
    switch (id) {
        case 1: return createDay<Day01, 1>();
        case 2: return createDay<Day02, 2>();
              :
        case 25: return createDay<Day25, 25>();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM