Choose template based on run-time string in C++

后端 未结 6 726
终归单人心
终归单人心 2020-12-14 11:39

I have an attribute vector that can hold different types:

class base_attribute_vector; // no template args

template
class raw_attribute_ve         


        
6条回答
  •  爱一瞬间的悲伤
    2020-12-14 12:20

    Largely based on Jarod42's answer, this is what I will be using:

    class base_attribute_vector {};
    
    template
    class raw_attribute_vector : public base_attribute_vector {
    public:
    raw_attribute_vector() {std::cout << typeid(T).name() << std::endl; }
    };
    
    template class impl>
    base* magic(std::string type) {
        if(type == "int") return new impl();
        else if(type == "float") return new impl();
    }
    
    int main() {
        auto x = magic("int");
        auto y = magic("float");
    }
    

提交回复
热议问题