3 ms·
An example from the article: auto f1 = std::bind(f, 2, n, _1); f1(10); // calls f(2, 5, 10); auto l1 = [ p1 = 2, p2 = n ](auto _1) { return std::invoke(f, p1
by rileymat2 9y ago
An example from the article:
auto f1 = std::bind(f, 2, n, _1);
f1(10); // calls f(2, 5, 10);
auto l1 = [ p1 = 2, p2 = n ](auto _1) { return std::invoke(f, p1, p2, _1); };
l1(10);
It seems to me std::bind is a lot cleaner syntactically.
- plorkyeran 9y agoThat's a literal translation of what std::bind() is doing that no one would actually write. `[n](auto a) { return f(2, n, a); }` is a more realistic way to write that lambda.
- jlarocco 9y agobind() is still the cleaner way to write it. Seeing std::bind tells me that the intention is to create a function that does nothing but call a second function with certain parameters fixed. A lambda expression is far more general, so when I see it I have to think about what it's doing. There's also a subtle implication that the author chose the more general technique for a reason. It'll raise the questions, "Why isn't this using std::bind()?", "Is there something else going on here?", etc. Off hand, I can't think of a reason why the bind would be any less efficient than the lambda.
- makecheck 9y agoAnd cleaner still is to not obfuscate things to this degree, no matter what syntax is involved. It certainly violates the “write once, read many times” principle: no matter how many times I look at something like this, I have to study the whole thing just to figure out what is even happening! Whereas, seeing "void g(x) { f(2, 5, x); }" is perfectly clear. It certainly violates the “premature optimization” principle: in exchange for some unproven benefit, the compiler does gymnastics to bind arguments and adds compile time instead of just paying a little more in space and runtime to define a 2nd function that calls a 1st function in a completely obvious way. It also qualifies as over-design. Even if a single binding is considered OK (and that’s a big “if”), there is every reason to expect that during normal maintenance someone will need to keep adding more. Then you have several lines of template-ese. A simple function is something that anyone can extend, whereas it’s not clear most engineers will even know how to maintain the binding version.
- solidsnack9000 9y agoI'm not sure how to read your comment. Are you saying not to use lambdas or closures, and just to define new functions?