193 points · by Tsiolkovsky · 12y ago · 134 comments
template<typename Range>
auto begin(Range& r) -> decltype(r.begin()) {
return r.begin();
}
The return type can't be specified by the function[0], and you have to copy and paste the body of the function into the decltype() clause to tell the compiler that the return type is whatever the thing it's wrapping returns. When you have some long and complicated expression rather than just r.begin() in the body, this duplication becomes a major issue.[0] In this specific case you could require that Range have an iterator typedef and return that, but that approach does not generalize.
If someone starts using auto for every variable or returning it from every method, then they need a stern talking-to.
It does not matter what the rationale behind the committee's decision was. This is standard practice in duck typed languages, and it will be adopted as well in C++, since it will be (imho, correctly) perceived as another step to bring C++ "to the 21th century".
You can stern-talk as much as you wish... but it won't have much effect unless backed up by an (effectively enforced) internal code style guide.
The barbarians are already at the gate. Which side are you going to pick?
Anyway, they are talking about documentation. Many people think that having to peek inside a function to know what it returns is worse than having a compiler-checked type declaration. In fact, in most languages with type inference there is still a strong convention to write full signatures for all top level functions, as a form of documentation (return type inference is left for lambdas)
Not only did you need to use the type correctly, but you needed to declare the desire to use a specific type from the get-go.
An auto return type means the type is inferred from the type of the expression that the function returns, so it's known from that.
Say I have a header file "foo.h" with an "auto foo();" declaration. Another file (eg, "bar.h") imports foo.h. How can the compiler do type checking when compiling bar.cc without also parsing foo.cc to determine the return type of foo()?
Requiring pointless verbosity on some hope that somehow that'll help bad programmers write better code seems like an odd conclusion.
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n363...:
Of course, using such a function in an expression when
only a forward declaration has been seen is ill-formed:
auto f(); // return type is unknown
int i = f(); // error, return type of f is unknown
And https://isocpp.org/wiki/faq/cpp14-language#generalized-retur...: Of course, this requires the function body to be visible.Its kind of weird to see people complaining about a C++ feature because its not appropriate to use indiscriminately and requires some discipline -- that's historically been pretty much the whole of C/C++.
map<unsigned int, map<int, vector<string>::iterator> >::iterator getSomeIterator();
or:
auto getSomeIterator();
Function name and context usually is sufficient to know what SomeIterator refers to, there is no need for horrible STL constructs to try to explain it.
I believe you don't need the space between the > > any more, since C++11?
std::map<unsigned int, std::map<int, std::vector<std::string>::iterator> >::iterator getSomeIterator();
MY_TYPE::iterator getSomeInterator();Then, we do use template parameters already, for which we usually don't know the type. I can't see why we'd bitch about 'auto' and not about the template parameters.
It's just the same thing: coding against interfaces and not implementations.
I prefer to make functions ordinary, and only templatize functions that need to operate on more than one type. There's good reasons for this: the compiler is less effective at type-checking templates, they require the function body to be visible, and they may fail to warn you when passed the wrong type.
"auto" suffers from all those problems, and yet we are being told to use it whenever possible. That's bad advice.
You have a point there
what you could do is:
return (int)x;
return (YourClass)value;
(then the header and implementation are auto but you still know what the code is talking about
(Or just put the type there as usual)
I love the rest of the changes, but that just doesn't sit right with me.
The standard can't use commas as a separator because using commas vs periods to demarcate components is locale specific. Apostrophes look like a reasonable compromise because lots of calculators already use apostrophes to separate digits:
https://www.google.com/search?q=14+digit+calculator&source=l...
So instead of 1,234.56789 (English) or 1.234,56789 (French) we do 1 234.56789 (international)
[0-9]+ [0-9]+ has no meaning in C++, so using space for magnitude decorations would have worked.
Dunno why they didn't use underscores though.
For example, the "->" was already an operator for pointer indirection but it was reused for lambda definitions. The "[]" was already used for array subscript indexes but was reused for lambda captures.
> ...
> [Code sample that returns -1 or record->id]
> Instead of using an integral type to identify the person in the record object, maybe I have a new GUID type. Making that change to the record object will cause a series of cascading changes in things like the return types of functions. But if my function uses automatic return type deduction, the compiler will silently make the change for me.
Yet when this happens, his example function can now return -1 or a GUID, so compilation should fail, no? Haven't worked with C++ in awhile so I might just be missing something on this, but seems like a contradiction to me.
One thing the C++ standard library IMO needs is a range library, e.g. something like Boost Range. I often would like to use the "range-for" but when I am not looping over all the elements of a container its useless in that case.
I agree about the range library, but it will be difficult to impossible to implement in the standard library without concepts. 2020 could be the year of range algorithms.
template<typename RANGE, typename PRED> void sort(RANGE, PRED);
and
template<typename ITERATOR> void sort(ITERATOR start, ITERATOR stop);
Since we already have the iterator algorithm defined, there is no room for a range algorithm name 'sort' with two template-deduced parameters. There are workarounds using enable_if, but they're hairy and involve basically recreating concepts at the standard library level.
Herb Sutter:
"I’m hopeful that the standard library will get range-based overloads of all standard algorithms that are enable_if’d to avoid the problem or can use concepts if those make it into a future standard."
http://herbsutter.com/2011/10/07/why-no-container-based-algo...
Why concepts then? The concepts version would look like:
template<Range, Comparator> void sort(Range & r, Comparator const & c);
...and the compiler would be able to tell that iterators wouldn't work with this algorithm.
So what are the nuances when comparing this approach to using a template to create a generic function? Aside from stylistic differences, would using one over the other affect compile time or runtime performance in any (meaningful) way?
Since when was a language spec put behind a paywall? I can't comprehend the reasoning behind this, given that open source compilers exist for C++. How much is it to view the spec? Why do they need to charge at all?
here is an explanation http://stackoverflow.com/questions/6815685/move-semantics-wh...
it is supposed to save extra copies like here
string a("a"); string b("b");
string c = a + b; // creates temporary object that is copied into C by value - the temporary is just a 'full copy'; so that for the temporary it needs an extra allocation and strcpy and free.
the fix is to add the following to the string class
string(string &&r) { ... }
string &operator=(string &&r) { ... }
so the operator with the && receives and 'rvalue' reference - which is a special reference to just this temprorary and the implementation of this is supposed to swap the data of the temporary with that of the this object; the temporary is then discarded.
[1] https://github.com/CppCon/CppCon2014/blob/master/Presentatio...
It says:
1. With deduction you always get right type
2. Deduction guarantees no implicit conversion will happen
From this we can conclude that "the right type" never involves an implicit conversion. This is false: see vector<bool>::operator[], or consider the fact that auto allows you to make a variable of a type you cannot name explicitly (i.e. is private), which is surely not "the right type!"
The biggest problem are the pre-C++98 codebases or the ones full with C idioms instead of modern C++.
Those aren't going away anytime soon.
Can you give some examples of methods in the standard library that should use const, but doesn't?
> The primary use-case of auto returns is for templated functions where the return type depends on the thing passed in.
Anyone know if compilers will support that?
Good changes, but too little, too late.
Of course, we still depend on it, but for an ever smaller set of use cases. Do what you have to do and "get out of there" as fast as you can to your favourite language.
This is of course personal preference, but also mostly because I realized (and it seems to me that some people haven't, just go around and ask what is C/C++, and people will tell you it's one language...) that C++ is not just anymore "C with classes", and the fact there is C-ish, or even just bad C++ code out in the wild doesn't make the language bad in itself (it can still be less appropriate/completely irrelevant for some applications, which is fine).
But sorry, I don't miss the includes, the huge class hierarchies, the template madness, etc
C++ is good if you stick to a strict code standard and don't let people "go crazy" with it.
But the thing is that good languages end up limiting the amount of "bad code" that naturally emerges. (Java does it through lack of flexibility and enforcement, I prefer the Python and Go way)
In the first years of C++ it was real joy to write software in it but now the syntax seems to be much more useful for obfuscation rather than maintainability.
Funny: When C++ began Ada 95 looked like a giant animal. Now Ada 2012 looks small and efficient in comparison although it is more powerful than Ada 95.
System programming languages need OS vendors support to thrive.
Support is provided by AdaCore for instance:
Everyone talks up Ada's safety, but they always seem to compare it to other Foogols, like C, C++, and Java/C#.
Which happens to be C++, until OS vendors support another one on their SDKs.
So until Ada, Rust, D, Swift, .NET Native or something else get such a position, C++ it is.
If you write your library in Perl, guess what, only people writing Perl will use it. If you write it in Java, well, maybe the Scala folk will wrap it up, or the Jython folk, but you won't get any people writing in Ruby to use it. If you write it in C++, you can provide efficient bindings to any of those languages.
For an example, look at FFmpeg or ImageMagick. They are libraries that just _won't die_, no matter how hard people have tried. My god, ImageMagick was written in 1987, and it now has Haskell bindings[0]! The only way to get that sort of longevity (and old code is good code, after all [1]) is to write in language that will outlast the ups and downs of the language or framework du jour, and C and C++ have proven to have that staying power. Yeah, they're terrible; I hate them. But there is a reason to use them.
[0] http://hackage.haskell.org/package/imagemagick
[1] http://www.joelonsoftware.com/articles/fog0000000069.html
- Another layer to debug (FFI)
- Possible loss of performance when crossing the FFI barrier
- Loss of productivity, because that cool API isn't available and so one has to write it
- Writing drivers, daemons/services, OS plugins, ...
One of the reasons I moved from Turbo Pascal to C++, when I started coding on Windows 3.0, was being fed up to write binding libraries by myself. Although I really enjoyed Turbo Pascal back then.
Yes, Rust looks VERY promising.