从模板创建对象,类型由用户输入c ++输入 [英] Create objects from template, type is entered by user input c++

查看:89
本文介绍了从模板创建对象,类型由用户输入c ++输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模板课程。我希望程序询问用户他想要什么类型,然后根据他选择的类型实例化一个对象。最好的方法是什么?像这样的东西,但是不起作用:

I have a class which is a template. I want the program to ask the user what type he wants and then instantiate an object based on the type he chose. What would be the best way to do this? Something like this, but it doesn't work:

template <typename T> class Object {...};
cin >> type;
Object<type> newobject;


推荐答案

多态



它将根据用户输入使对象模板基于动态:

Polymorphism

it will make objects template based and dynamic based on user input:

class Base
{
public:
  virtual ~Base() {};
};

template <typename T>
class Type : public Base
{
    T type;
};

int main()
{
    int i;
    cin >> i;

    Base *b;

    switch (i)
    {
    case 0: b = new Type<float>(); break;
    case 1: b = new Type<int>(); break;
    case 2: b = new Type<char>(); break;
    }

    // ...

    delete b;
}

这篇关于从模板创建对象,类型由用户输入c ++输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆