News for hackers. Stuff that matters.
Re:The Gang of Four book is wrong about delegation (2012) by humanrebar on Thursday June 29, 2017 @04:39PM (#14666682)
> And C++ can't do delegation

Sure it can. The syntax is a little different, though. And there are a few ways to do it. Here's one:

    #include <iostream>
    #include <functional>

    struct Container {
        template <typename Self>
        void announce(Self const & self) const
        {
            std::cout << "these are my things: "
                      << self.things << '\n';
        }
    };

    struct Bucket {        
        std::string things;
        std::function <void()> announce;

        template <typename Delegate>
        explicit Bucket(
            Delegate const & delegate,
            std::string const& aThings) :
                things(aThings),
                announce([&](){ delegate.announce(*this); } )
        { }
    };

    int main()
    {
        // Container works with anything with a 'things'
        // attribute
        Container container;
        // Bucket takes anything with an announce method
        // that accepts a Bucket-like object
        Bucket bucket(
            container,
            "planes, trains, and automobiles"
        );
        bucket.announce();
        return 0;
    }

There are no comments on this comment yet.