tomKPZ
tomKPZ

Reputation: 837

c++ - Calling a function for all members of a specific type

I have a class C with a member function f. Users may create their own classes with several C's as members. I'd like to be able to call f for every member of type C in a user-defined class. The problem is I can't figure out how to implement this without the users having to provide a function like this:

void UserClass::callFonEveryCmember(void) {
    c1.f();
    c2.f();
    ...
}

Is there any way that I can achieve this?

Upvotes: 2

Views: 257

Answers (2)

Mateusz Kacprzak
Mateusz Kacprzak

Reputation: 293

class UserClass
{
    ...
    vector<C*> v;
}

void UserClass::callFonEveryCmember(void)
{
    for (unsigned i = 0; i < v.size(); ++i) {
        v.at[i]->f();
    }
}

Upvotes: 0

rogierschouten
rogierschouten

Reputation: 153

C++ doesn't have reflection like e.g. C# if that's what you're after. What I've done in the past is to generate C++ code from a class description and then also generate reflection code with it. I.e. your users would be making class descriptions rather than classes.

The short-term solutions I see are 1) Have a function like you describe above 2) Rather than separate member, use one member with a vector of c's.

Upvotes: 2

Related Questions