How can I declare a template pointer without knowing the type?

后端 未结 3 1426
孤城傲影
孤城傲影 2021-02-01 19:27

This is what I would like to do:

ExampleTemplate* pointer_to_template;
cin >> number;
switch (number) {
case 1:
    pointer_to_template = new ExampleTempla         


        
3条回答
  •  无人共我
    2021-02-01 20:18

    You can do something similar by having your template class derive from a regular class:

    #include
    #include
    using namespace std;
    
    class ExampleBase{
    
    public:
        virtual ~ExampleBase() {}
        virtual string Get() = 0;
    };
    
    template
    class ExampleTemplate : public ExampleBase{
    
    private:
        T data;
    
    public:
        ExampleTemplate(T t) : data(t){}
    
        string Get(){        
            stringstream s; s << data;
            return s.str();
        }
    
    };
    
    int main(){
    
        ExampleBase *base;
        int number;
        cout << "> " << flush; cin >> number;
    
        switch(number){
            case 1:
                base = new ExampleTemplate(42);
                break;
            case 2:
                base = new ExampleTemplate(3.14);
                break;
            default:
                return 1;
        }
    
        cout << base->Get() << endl;
    
        delete base;
        return 0;
    }
    

提交回复
热议问题