Reputation: 310
I have a vector of unique_ptr<my_class>
and would like to be able to pass to a function the member variable of this class I'd like to output. This vector is part of a class in itself.
For example I would like to
void my_top_class::output_member(sometype var_to_output, std::ofstream &out)
{
// Iterate over the vector and output the member variable
out << my_class->var_to_output << std::endl;
// Or something similar
}
And then just do
my_top_class.output_member(var1, file_out);
my_top_class.output_member(var2, file_out);
At the moment I have a separate function for each member variable and this feels cumbersome
Upvotes: 1
Views: 69
Reputation: 7491
Use pointer to data members (it is only an example, you should adopt it to your situation):
template <typename MemberType>
void output_member(const MyClass& my_object, MemberType MyClass::* var_to_output)
{
std::cout << my_object.*var_to_output << std::endl;
}
Here .*
is one of pointer to member access operators.
Example of using:
struct MyClass
{
int member_variable_;
};
// ...
MyClass my_object{42};
output_member(my_object, &MyClass::member_variable_);
Upvotes: 2
Reputation: 241
Maybe just create a new class that you will use to store your elemets? Like this:
class Memory
{
private:
std::vector<yourclass> vec;
public:
std::vector<yourclass> getVector()
{
return vec;
}
};
Then create an object of that class in your main class main window, whatever you are using. Actually you didn't provide too much information and it is hard to answer your question.
Upvotes: 0