super generic functions in c++14

Since C++14 lambdas now allow auto parameters, function objects can be pretty damn generic.

[](auto&& arg1, auto&& arg2) { return arg1 < arg2; }

Which got me thinking, what’s to stop me from defining all of my functions as lambdas. For example, this function which takes an iterable and prints it to stdout.

auto print_iterable = [](auto&& iterable) {
    for (auto&& e : iterable) {
        std::cout << e << '\n';
    }
};

int main() {
    std::vector<int> v{1,7,2,0};
    print_iterable(v);
}

This function can deduce its argument types and return type. There’s no return here of course, but there’s nothing stopping me from making this function more complex.

I haven’t thought too much about the implications of this, but it seems like I could get away without naming variable types or using templates. I’m not saying this a good idea, but it’s an interesting one.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s