Storing templated objects in a vector (Storing Class, Class in a single vector)

前端 未结 2 993
情书的邮戳
情书的邮戳 2021-01-20 22:25

There is a templated class, let it be

template class A { std::vector data; };

The problem I am facing here is,

2条回答
  •  面向向阳花
    2021-01-20 22:56

    As previous comments stated - you first need to make sure this is what you need.

    With that been said, I had a similar requirement in a project of mine, which I eventually solved with inheritance and PIMPL, as follows:

    class A{
    private:
        struct Abstract {
            virtual void f() = 0;
        };
    
        template 
        struct Implementation : public Abstract {
            std::vector data;
            virtual void f() {...}
        };
    
        std::unique_ptr impl;
    
    public:
        template 
        A(): impl(std::make_unique >()){}
    
        void f() {impl->f();}
    };
    

    This allows you to create a container of objects of type A, and access them via the public interface defined therein (the method f). The underlying type T of each A object is specified on construction. All other implementation details specific to the type T are hidden.

    The solution suffers the inherent overhead of virtual functions. I'm not sure how it compares to the std::any approach performance-wise.

提交回复
热议问题