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

后端 未结 3 1420
孤城傲影
孤城傲影 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:12

    You can't. ExampleTemplate and ExampleTemplate are two different, unrelated types. If you always have a switch over several options, use boost::variant instead.

    typedef boost::variant, Example> ExampleVariant;
    ExampleVariant v;
    switch (number) {
        case 1: v = Example(); break;
        case 2: v = Example(); break;
    }
    // here you need a visitor, see Boost.Variant docs for an example
    

    Another way is to use an ordinary base class with virtual public interface, but I'd prefer variant.

    struct BaseExample {
        virtual void do_stuff() = 0;
        virtual ~BaseExample() {}
    };
    
    template 
    struct Example : BaseExample { ... };
    
    // ..
    BaseExample *obj;
    

提交回复
热议问题