Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 929277
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T20:08:40+00:00 2026-05-15T20:08:40+00:00

Situation I want to implement the Composite pattern: class Animal { public: virtual void

  • 0

Situation

I want to implement the Composite pattern:

class Animal
{
public:
    virtual void Run() = 0;
    virtual void Eat(const std::string & food) = 0;
    virtual ~Animal(){}
};

class Human : public Animal
{
public:
    void Run(){ std::cout << "Hey Guys I'm Running!" << std::endl; }
    void Eat(const std::string & food)
    {
        std::cout << "I am eating " << food << "; Yummy!" << std::endl;
    }
};

class Horse : public Animal
{
public:
    void Run(){ std::cout << "I am running real fast!" << std::endl; }
    void Eat(const std::string & food)
    {
        std::cout << "Meah!! " << food << ", Meah!!" << std::endl;
    }
};

class CompositeAnimal : public Animal
{
public:
    void Run()
    {
        for(std::vector<Animal *>::iterator i = animals.begin();
            i != animals.end(); ++i)
        {
            (*i)->Run();
        }
    }

    // It's not DRY. yuck!
    void Eat(const std::string & food)
    {
        for(std::vector<Animal *>::iterator i = animals.begin();
            i != animals.end(); ++i)
        {
            (*i)->Eat(food);
        }
    }

    void Add(Animal * animal)
    {
        animals.push_back(animal);
    }

private:
    std::vector<Animal *> animals;
};

The Problem

You see, for my simple requirement of the composite pattern, I end up writing a lot of the same repeating code iterating over the same array.

Possible solution with macros

#define COMPOSITE_ANIMAL_DELEGATE(_methodName, _paramArgs, _callArgs)\
    void _methodName _paramArgs                                      \
    {                                                                \
        for(std::vector<Animal *>::iterator i = animals.begin();     \
            i != animals.end(); ++i)                                 \
        {                                                            \
            (*i)->_methodName _callArgs;                             \
        }                                                            \
    }

Now I can use it like this:

class CompositeAnimal : public Animal
{
public:
    // It "seems" DRY. Cool

    COMPOSITE_ANIMAL_DELEGATE(Run, (), ())
    COMPOSITE_ANIMAL_DELEGATE(Eat, (const std::string & food), (food))

    void Add(Animal * animal)
    {
        animals.push_back(animal);
    }

private:
    std::vector<Animal *> animals
};

The question

Is there a way to do it “cleaner” with C++ meta-programming?

The harder question

std::for_each has been suggested as a solution. I think our problem here is a specific case of the more general question, let’s consider our new macro:

#define LOGGED_COMPOSITE_ANIMAL_DELEGATE(_methodName, _paramArgs, _callArgs)\
    void _methodName _paramArgs                                      \
    {                                                                \
        log << "Iterating over " << animals.size() << " animals";    \
        for(std::vector<Animal *>::iterator i = animals.begin();     \
            i != animals.end(); ++i)                                 \
        {                                                            \
            (*i)->_methodName _callArgs;                             \
        }                                                            \
        log << "Done"                                                \
    }

Looks like this can’t be replaced by for_each

Aftermath

Looking at GMan’s excellent answer, this part of C++ is definitely non-trivial. Personally, if we just want to reduce the amount of boilerplate code, I think macros probably is the right tool for the job for this particular situation.

GMan suggested std::mem_fun and std::bind2nd to return functors. Unfortunately, this API doesn’t support 3 parameters (I can’t believe something like this got released into the STL).

For illustrative purpose, here’re the delegate functions using boost::bind instead:

void Run()
{
    for_each(boost::bind(&Animal::Run, _1));
}

void Eat(const std::string & food)
{
    for_each(boost::bind(&Animal::Eat, _1, food));
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T20:08:41+00:00Added an answer on May 15, 2026 at 8:08 pm

    I’m not sure I really see the problem, per se. Why not something like:

    void Run()
    {
        std::for_each(animals.begin(), animals.end(),
                        std::mem_fun(&Animal::Run));
    }
    
    void Eat(const std::string & food)
    {
        std::for_each(animals.begin(), animals.end(),
                        std::bind2nd(std::mem_fun(&Animal::Eat), food));
    }
    

    Not too bad.


    If you really wanted to get rid of the (small) boilerplate code, add:

    template <typename Func>
    void for_each(Func func)
    {
        std::for_each(animals.begin(), animals.end(), func);
    }
    

    As a private utility member, then use that:

    void Run()
    {
        for_each(std::mem_fun(&Animal::Run));
    }
    
    void Eat(const std::string & food)
    {
        for_each(std::bind2nd(std::mem_fun(&Animal::Eat), food));
    }
    

    A bit more concise. No need for meta-programming.

    In fact, meta-programming will ultimately fail. You’re trying to generate functions, which are defined textually. Meta-programming cannot generate text, so you’ll inevitably use a macro somewhere to generate text.

    At the next level, you’d write the function then try to take out the boilerplate code. std::for_each does this quite well. And of course as has been demonstrated, if you find that to be too much repetition, just factor that out as well.


    In response to the LoggedCompositeAnimal example in the comment, your best bet is to make something akin to:

    class log_action
    {
    public:
        // could also take the stream to output to
        log_action(const std::string& pMessage) :
        mMessage(pMessage),
        mTime(std::clock())
        {
            std::cout << "Ready to call " << pMessage << std::endl;
        }
    
        ~log_action(void)
        {
            const std::clock_t endTime = std::clock();
    
            std::cout << "Done calling " << pMessage << std::endl;
            std::cout << "Spent time: " << ((endTime - mTime) / CLOCKS_PER_SEC)
                        << " seconds." << std::endl;
        }
    
    private:
        std::string mMessage;
        std::clock_t mTime;
    };
    

    Which just mostly automatically logs actions. Then:

    class LoggedCompositeAnimal : public CompositeAnimal
    {
    public:
        void Run()
        {
            log_action log(compose_message("Run"));
            CompositeAnimal::Run();
        }
    
        void Eat(const std::string & food)
        {
            log_action log(compose_message("Eat"));
            CompositeAnimal::Eat(food);
        }
    
    private:
        const std::string compose_message(const std::string& pAction)
        {
            return pAction + " on " +
                        lexical_cast<std::string>(animals.size()) + " animals.";
        }
    };
    

    Like that. Information on lexical_cast.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

The situation is like this. class Interface { public: virtual void foo() = 0;
Introductory OOP question for you: Situation: I want an abstract class with a public
I have a situation where i want to return List<> from this function public
I'm writing a custom iterator for a Matrix class, and I want to implement
I want to implement in Java a class for handling graph data structures. I
Simple situation One object User have many UserGroups. I want to implement on mvc3
Situation: I want to provide a website service where users can enter some data
I have a sort of unique situation....I want to populate a ModelChoiceField based of
So the situation is: I want to optimize my code some for doing counting
I have a situation where I want a bash script to replace an entire

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.