Dat Tran
Dat Tran

Reputation: 57

Possible create an array of different structures in C++

I have some struct like this:

struct A { ... };
struct B { ... };

And I have a template like this:

template<typename struct_arg>
class X { ... }

Now I wanna create an array of arguments as struct like this:

args [2] { A, B };

for (args) {
    X<args[i]> x;
}

Can I possible to create an array like this!?

Upvotes: 2

Views: 80

Answers (1)

Klaus
Klaus

Reputation: 25613

Yes, you can do. std::variant is made for this usage and you can access such members of a variant with std::visit.

But if you do so, keep in mind, that each element of the array has an additional data member which has the type information and that each element has at minimum the size of the largest type you store. And also std::visit comes with a overhead, as a table for access the data member must be created. Typically done in compile time, but sometime g++ generates it in run time, which will decrease speed a lot!

struct A
{
    void Do() { std::cout << "A" << std::endl; }
};  

struct B
{
    void Do() { std::cout << "B" << std::endl; }
};  

int main()
{   
    std::array<std::variant< A,B >,2> arr{ A{}, B{}, B{}, A{} };

    for ( auto& element: arr )
    {   
        std::visit( []( auto& vari ) { vari.Do(); }, element );
    }   
}  

Or if you like your encapsulation with an additional strucuture/class like given in your example:

struct A
{
    void Do() { std::cout << "A" << std::endl; }
};

struct B
{
    void Do() { std::cout << "B" << std::endl; }
};

template < typename struct_arg >
struct X: public struct_arg{};


int main()
{
    std::array<std::variant< X<A>,X<B> >,2> arr{ X<A>{}, X<B>{} };

    for ( auto& element: arr )
    {
        std::visit( []( auto& vari ) { vari.Do(); }, element );
    }
}

Upvotes: 2

Related Questions