Vector of different specializations of a templated class

后端 未结 1 1218
囚心锁ツ
囚心锁ツ 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 
    #include 
    
    using std::cout;
    using std::endl;
    
    
    class Mother {
    public:
        virtual void doSomeThing() = 0;
    };
    
    template
    class Child : public Mother {
        void doSomeThing() override;
    };
    
    template void Child::doSomeThing() {
        cout << "Base Function" << endl;
    }
    template<> void Child::doSomeThing() {
        cout << "Int template" << endl;
    }
    
    template<> void Child::doSomeThing() {
        cout << "Float template" << endl;
    }
    
    int main() {
    
        std::vector> vec;
    
        vec.emplace_back(new Child());
        vec.emplace_back(new Child());
        vec.emplace_back(new Child());
    
        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)
提交回复
热议问题