Vector of different specializations of a templated class

后端 未结 1 1217
囚心锁ツ
囚心锁ツ 2021-01-26 06:11

Since I have been using templates in C++, I often encounter this problem: I would like to gather instances of different versions of a templated class in a vector.

I unde

相关标签:
1条回答
  • 2021-01-26 06:41

    If you want to store different template classes, you can make a parent class and inherit that class in the template class.

    And I don't know why you're using switch for types, just use template instantiation.

    #include <iostream>
    #include <vector>
    
    using std::cout;
    using std::endl;
    
    
    class Mother {
    public:
        virtual void doSomeThing() = 0;
    };
    
    template<typename T>
    class Child : public Mother {
        void doSomeThing() override;
    };
    
    template<typename T> void Child<T>::doSomeThing() {
        cout << "Base Function" << endl;
    }
    template<> void Child<int>::doSomeThing() {
        cout << "Int template" << endl;
    }
    
    template<> void Child<float>::doSomeThing() {
        cout << "Float template" << endl;
    }
    
    int main() {
    
        std::vector<std::unique_ptr<Mother>> vec;
    
        vec.emplace_back(new Child<double>());
        vec.emplace_back(new Child<int>());
        vec.emplace_back(new Child<float>());
    
        vec[0]->doSomeThing();
        vec[1]->doSomeThing();
        vec[2]->doSomeThing();
    
    
        return 0;
    }
    

    output:

    Base Function
    Int template
    Float template
    
    Process finished with exit code 0
    
    0 讨论(0)
提交回复
热议问题