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

前端 未结 2 992
情书的邮戳
情书的邮戳 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 <typename T>
        struct Implementation : public Abstract {
            std::vector<T> data;
            virtual void f() {...}
        };
    
        std::unique_ptr<Abstract> impl;
    
    public:
        template <typename T>
        A(): impl(std::make_unique<Implementation<T> >()){}
    
        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.

    0 讨论(0)
  • 2021-01-20 23:05

    std::any is the modern c++17 solution. Specifically, you should use

    A<int> a;
    a.data.push_back(0);
    
    // fill refernces...
    std::vector<std::any> refernces; 
    refernces.push_back(&a.data[0]);
    
    // check which type is active.
    if(int** iPtr = std::any_cast<int*>(&references[0]); iPtr != nullptr)
    {
         // its an int*
         int& i = **iPtr;
         // do something with i.
    }
    

    These pointers can point into the A<int>::data and A<double>::data vectors.

    For a complete reference, see here https://en.cppreference.com/w/cpp/utility/any.

    0 讨论(0)
提交回复
热议问题