oxidising oxidising - 3 months ago 10
C++ Question

Outputting a member of a vector of classes

I have two classes

class MyStoreClass
{
public:
std::vector<std::unique_ptr<MyClass>> my_vec;
};


and

class MyClass
{
public:
double member1;
int member2;
};


I have a vector of around 10000 MyClasses
I would like to be able to use a function such as

template<typename T>
void MyStoreClass::output_member(T MyClass::* chosen_member)
{
std::cout << chosen_member << std::endl;
}


I'm not really sure where to go from here.

Edit: I'd like to output
member
from each MyClass in the vector

Answer

You forgot to describe what the function should do, so I'm assuming that you want the function to print the corresponding member of all elements of my_vec.

You need to explicitly dereference the unique_ptr in order to use the pointer-to-member dereferencing operator.
The rest is straightforward:

template<typename T>
void MyStoreClass::output_member(T MyClass::* chosen_member)
{
    for (const auto& ptr: my_vec)
    {
        if (ptr)
            std::cout << (*ptr).*chosen_member << std::endl;
        else
            std::cout << "[null]" << std::endl;
    }
}
Comments