创建动态推导类型的智能指针?

问题描述 投票:0回答:1

是否可以在不使用 if 序列的情况下创建动态推导类型的指针?

我应该使用什么作为地图值类型?

class Vehicle {
  public:
    virtual void run() =0;
};

// Derived class
class Mustang: public Vehicle {
  public:
    string model = "Mustang";
    virtual void run() {std::cout<<model<<std::endl;};
};

// Derived class
class Ford: public Vehicle {
  public:
    string model = "Ford";
    virtual void run() {std::cout<<model<<std::endl;};
};

std::unordered_map<std::string, std::type_index> m {{"Mustang",typeid(Mustang)},{"Ford",typeid(Ford)} };

int main()
{
    std::unique_ptr<Vehicle> v;
    std::string s{"Mustang"};
    
    v=std::make_unique<m.at(s)>;
    v->run(); //what i want to achieve is print "Mustang"

    return 0;
}
c++ templates metaprogramming smart-pointers
1个回答
1
投票

您可以在地图中存储返回

std::unique_ptr<Vehicle>
的可调用对象:

#include <string>
#include <memory>
#include <iostream>
#include <unordered_map>
#include <functional>

class Vehicle {
  public:
    virtual void run() =0;
};

// Derived class
class Mustang: public Vehicle {
  public:
    std::string model = "Mustang";
    virtual void run() {std::cout<<model<<std::endl;};
};

// Derived class
class Ford: public Vehicle {
  public:
    std::string model = "Ford";
    virtual void run() {std::cout<<model<<std::endl;};
};

std::unordered_map<std::string, std::function<std::unique_ptr<Vehicle>()>> m {
    {"Mustang",[]()->std::unique_ptr<Vehicle> { return std::make_unique<Mustang>();}},
    {"Ford",[]() ->std::unique_ptr<Vehicle> { return std::make_unique<Ford>();}} 
    };

int main()
{
    std::unique_ptr<Vehicle> v;
    std::string s{"Mustang"};
    
    v=m.at(s)();
    v->run(); //what i want to achieve is print "Mustang"

    return 0;
}

现场演示


这个:

[]()->std::unique_ptr<Vehicle> { return std::make_unique<Mustang>();}

相当冗长,因此可能需要编写一个辅助函数:

template <typename T> 
std::unique_ptr<Vehicle> create_vehicle() {
       return std::make_unique<T>();
}
© www.soinside.com 2019 - 2024. All rights reserved.