Jan 23, 2015

[C++] Sean Parent for_each_argument style

for_each_argument—Sean Parent
#include <iostream>
#include <string>

struct ToString
{
    virtual std::string toString()=0;
};


struct Cpp final : ToString
{
    std::string toString() override
    {
        return "I am a C++ enthusiast.";
    }
};


struct Java final : ToString
{
    std::string toString() override
    {
        return "I currently coding in Java with stealth-mode project.";
    }
};


struct Python final : ToString
{
    std::string toString() override
    {
        return "I use Python for automation.";
    }
};


template<typename T>
void print(T&& t)
{
    std::cout << t.toString() << std::endl;
}


template <class F, class... Args>
void for_each_argument(F f, Args&&... args) {
    [](...){}( ( f(std::forward<Args>(args)), 0)... );
}


int main()
{
    for_each_argument(
        [](auto&& arg)
        {
            print(std::forward<decltype(arg)>(arg));
        },
        Cpp{}, Java{}, Python{}
        );
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.