4 ms·
As many on the /r/cpp thread for this said, the ultimate result: auto x = int(foo(blah)); is no shorter than the version with an explicit template paramet
by quietbritishjim 6y ago
As many on the /r/cpp thread for this said, the ultimate result:
auto x = int(foo(blah));
is no shorter than the version with an explicit template parameter for the return type:
auto x = foo<int>(blah);
That doesn't apply to situations where you can genuinely take advantage of the implicit conversion:
takes_int_param(foo(blah));
But frankly the extra typing in an explicit version is worth it for improved code clarity:
takes_int_param(foo<int>(blah));
That's just if you get it right - if you get something wrong and end up with a compiler error, the error message for the implicit conversion is going to be far more complex than for an explicit return type parameter.
- DanielBMarkham 6y agoYes. I agree. I thought the essay might be useful or informative, but about a third of the way through I realized that this was one of these "look how clever I am" essays. This would have been a good launching-off point to talk about the linker, or language design, which we did a bit of towards the end but in the wrong context, in my opinion. Instead this author was a bit too clever by half; a shorter article more focused on practical limitations might have been much more helpful to coders.
- Animats 6y ago> "look how clever I am" essays. Yes. If you had general overload on return type, you could write big nested expressions and force the compiler to examine all the overload possibilities. With enough effort, you could write optimizers for functional programming that way, ones that figured out when you can create a pipeline and avoid storing an intermediate result. Plus combinatoric explosion in compile times. And then you would need more advanced algorithms to find a path through the type maze efficiently. What fun! Good for at least three PhD theses. Don't go there. Someone will have to maintain that code.
- gpderetta 6y agoThe return-type overloading helps if you want to use non-static member initialization: struct Foo { int x = init("x"); double y = init("y"); string z = init("z"); }; for not very good reasons you can't use auto there and having to specify the type twice is ugly. edit: this is pretty much the only case I have used this trick.
- ot 6y agoYeah, this is something that might have made sense before auto, and in fact IIRC there were some Boost libraries that used this trick (Boost.Assign?), but it's just unnecessary complication at this point.