Why is there a sizeof... operator in C++0x? - c++

I saw that #GMan implemented a version of sizeof... for variadic templates which (as far as I can tell) is equivalent to the built in sizeof.... Doesn't this go against the second design principle: prefer libraries to language extensions?

From Variadic Templates (Revision 3)
(N2080=06-0150), page 6:
Although not strictly necessary (we can implement count without this feature), checking the length of a parameter pack is a common operation that deserves a simple syntax. Moreover, this operation may become necessary for type-checking reasons when variadic templates are combined with concepts; see Section 3.3.
(Section 3.3 talks about concepts which is irrelevant now.)

sizeof... is just sugar, I think.
sizeof is indeed core to the language as is ..., and although a countof function could exist we already have sizeof and ... reserved so we might as well make it convenient to get the count that way.
Contrarily, if sizeof and ... weren't reserved, the idea of adding such a thing would have probably failed because new keywords tend to be frowned upon. (The less the better.)

Related

What are the use cases of C++20 Concepts?

I found about Concepts while reviewing C++20 features. I found that they add validation to templates arguments but apart from that I don't understand what are the real world use cases of C++20 concepts.
C++ already has things like std::is_integral and they can perform validation very well.
I'm sure I am missing something about C++20 concepts and what it enables.
SFINAE (see here & here) was an accidentally Turing complete sublanguage that executes at overload resolution and template specialization selection time.
Turns out it is used a lot in template code.
Concepts and requires clauses are an attempt to take that accidentally useful language feature and make it suck less.
The origin of concepts was going to have 3 pieces; (a) describing what is required for a given bit of template code in a clean way, (b) also provide a way to map other types to satisfy those requirements non-intrusively, and (c) check template code so that any type which satisfies the concept is guaranteed to compile
All attempts at (a) plus (c) sucked, usually taking forever to compile and/or restricting what you can check with (a). (b) was also dropped to ensure (a) was better; you can write such concept map machinery manually in many cases, but C++ doesn't provide it for you.
So, now what is it good for?
auto sum( Addable auto... values )
that uses the concept of Addable to concisely express an interface of a template. Error messages you get when passing a non-addable highlight it isn't Addable, and the expression that doesn't work.
template<class T, class A>
struct vector{
bool operator==(vector<t,A>const& o)requires EquallyComparible<T>;
};
here, we state this vector has a == if and only if the T does. Doing this before concepts is an annoying undertaking, and even adding the specs to the standard is.
This is the turing tar pit; everyting is equivalent, but nothing is easy. All programs can be written with I/O plus a (a=(a-b);(a<0)?goto c:next 3 argument instruction; but a richer language makes programs suck less. Concepts takes an esoteric branch of C++, SFINAE, and makes it clean and simpler (so more people can leverage it), and improves error messages.

Why is std::is_pod deprecated in C++20?

std::is_pod will be probably deprecated in C++20.
What's the reason for this choice? What should I use in place of std::is_pod to know if a type is actually a POD?
POD is being replaced with two categories that give more nuances. The c++ standard meeting in november 2017 had this to say about it:
Deprecating the notion of “plain old data” (POD). It has been replaced with two more nuanced categories of types, “trivial” and “standard-layout”. “POD” is equivalent to “trivial and standard layout”, but for many code patterns, a narrower restriction to just “trivial” or just “standard layout” is appropriate; to encourage such precision, the notion of “POD” was therefore deprecated. The library trait is_pod has also been deprecated correspondingly.
For simple data types use the is_standard_layout function, for trivial data types (such as simple structs) use the is_trivial function.

Is there anything else to std::cbegin() other than begin()ing a const reference?

I'm constrained to writing C++11 code, but I want to use std::cbegin(). So, I'm looking at GCC 5.4.0's implementation, in /usr/include/c++/5/bits/range_access.h on my system, thinking I might write something similar, and I see:
template<class _Container>
inline constexpr auto
cbegin(const _Container& __cont) noexcept(noexcept(std::begin(__cont)))
-> decltype(std::begin(__cont))
{ return std::begin(__cont); }
is that all there is to it? Am I missing something? If that's it, how come it wasn't part of C++11 like std::begin()?
is that all there is to it?
Yes.
Am I missing something?
Not that I'm aware of.
If that's it, how come it wasn't part of C++11 like std::begin()?
The global templates seem to have been part of the original proposal as an alternative to the member functions, but the proposal preferred to only provide the member functions in favour of providing either just the global templates, or both the templates and members. (Assuming this is the original proposal: N1674).
The committee chose to include the member function alternative in C++11, and the template not until C++14. I'm not part of the committee, and cannot speak for them, but my guess is that the attitude of the proposal may have affected the decision:
While this generic adapter alternative seems quite straightforward, we nonetheless favor the
member function approach as proposed above. It seems more in keeping with current C++
programming idioms, such as the parallel use of
rbegin
as a container member function rather
than as a generic adapter
Here is the development for the C++ Standard Library Defect Report issue (2128) where the template versions were decided to be adopted into C++14 after all.
No, that covers it.
Although a small function can be added to the standard with a relatively small amount of effort, time is finite and the committee doesn't have unlimited resource. Another example of a reasonably useful and trivial function that was omitted until C++14 is std::make_unique. Things improve over time.

Why isn't std::initializer_list a language built-in?

Why isn't std::initializer_list a core-language built-in?
It seems to me that it's quite an important feature of C++11 and yet it doesn't have its own reserved keyword (or something alike).
Instead, initializer_list it's just a template class from the standard library that has a special, implicit mapping from the new braced-init-list {...} syntax that's handled by the compiler.
At first thought, this solution is quite hacky.
Is this the way new additions to the C++ language will be now implemented: by implicit roles of some template classes and not by the core language?
Please consider these examples:
widget<int> w = {1,2,3}; //this is how we want to use a class
why was a new class chosen:
widget( std::initializer_list<T> init )
instead of using something similar to any of these ideas:
widget( T[] init, int length ) // (1)
widget( T... init ) // (2)
widget( std::vector<T> init ) // (3)
a classic array, you could probably add const here and there
three dots already exist in the language (var-args, now variadic templates), why not re-use the syntax (and make it feel built-in)
just an existing container, could add const and &
All of them are already a part of the language. I only wrote my 3 first ideas, I am sure that there are many other approaches.
There were already examples of "core" language features that returned types defined in the std namespace. typeid returns std::type_info and (stretching a point perhaps) sizeof returns std::size_t.
In the former case, you already need to include a standard header in order to use this so-called "core language" feature.
Now, for initializer lists it happens that no keyword is needed to generate the object, the syntax is context-sensitive curly braces. Aside from that it's the same as type_info. Personally I don't think the absence of a keyword makes it "more hacky". Slightly more surprising, perhaps, but remember that the objective was to allow the same braced-initializer syntax that was already allowed for aggregates.
So yes, you can probably expect more of this design principle in future:
if more occasions arise where it is possible to introduce new features without new keywords then the committee will take them.
if new features require complex types, then those types will be placed in std rather than as builtins.
Hence:
if a new feature requires a complex type and can be introduced without new keywords then you'll get what you have here, which is "core language" syntax with no new keywords and that uses library types from std.
What it comes down to, I think, is that there is no absolute division in C++ between the "core language" and the standard libraries. They're different chapters in the standard but each references the other, and it has always been so.
There is another approach in C++11, which is that lambdas introduce objects that have anonymous types generated by the compiler. Because they have no names they aren't in a namespace at all, certainly not in std. That's not a suitable approach for initializer lists, though, because you use the type name when you write the constructor that accepts one.
The C++ Standard Committee seems to prefer not to add new keywords, probably because that increases the risk of breaking existing code (legacy code could use that keyword as the name of a variable, a class, or whatever else).
Moreover, it seems to me that defining std::initializer_list as a templated container is quite an elegant choice: if it was a keyword, how would you access its underlying type? How would you iterate through it? You would need a bunch of new operators as well, and that would just force you to remember more names and more keywords to do the same things you can do with standard containers.
Treating an std::initializer_list as any other container gives you the opportunity of writing generic code that works with any of those things.
UPDATE:
Then why introduce a new type, instead of using some combination of existing? (from the comments)
To begin with, all others containers have methods for adding, removing, and emplacing elements, which are not desirable for a compiler-generated collection. The only exception is std::array<>, which wraps a fixed-size C-style array and would therefore remain the only reasonable candidate.
However, as Nicol Bolas correctly points out in the comments, another, fundamental difference between std::initializer_list and all other standard containers (including std::array<>) is that the latter ones have value semantics, while std::initializer_list has reference semantics. Copying an std::initializer_list, for instance, won't cause a copy of the elements it contains.
Moreover (once again, courtesy of Nicol Bolas), having a special container for brace-initialization lists allows overloading on the way the user is performing initialization.
This is nothing new. For example, for (i : some_container) relies on existence of specific methods or standalone functions in some_container class. C# even relies even more on its .NET libraries. Actually, I think, that this is quite an elegant solution, because you can make your classes compatible with some language structures without complicating language specification.
This is indeed nothing new and how many have pointed out, this practice was there in C++ and is there, say, in C#.
Andrei Alexandrescu has mentioned a good point about this though: You may think of it as a part of imaginary "core" namespace, then it'll make more sense.
So, it's actually something like: core::initializer_list, core::size_t, core::begin(), core::end() and so on. This is just an unfortunate coincidence that std namespace has some core language constructs inside it.
Not only can it work completely in the standard library. Inclusion into the standard library does not mean that the compiler can not play clever tricks.
While it may not be able to in all cases, it may very well say: this type is well known, or a simple type, lets ignore the initializer_list and just have a memory image of what the initialized value should be.
In other words int i {5}; can be equivalent to int i(5); or int i=5; or even intwrapper iw {5}; Where intwrapper is a simple wrapper class over an int with a trivial constructor taking an initializer_list
It's not part of the core language because it can be implemented entirely in the library, just line operator new and operator delete. What advantage would there be in making compilers more complicated to build it in?

Difference between decltype and typeof?

Two question regarding decltype and typeof:
Is there any difference between the decltype and typeof operators?
Does typeof become obsolete in C++11?
There is no typeof operator in c++. While it is true that such a functionality has been offered by most compilers for quite some time, it has always been a compiler specific language extension. Therefore comparing the behaviour of the two in general doesn't make sense, since the behaviour of typeof (if it even exists) is extremely platform dependent.
Since we now have a standard way of getting the type of a variable/expression, there is really no reason to rely on non portable extensions, so I would say it's pretty much obsolete.
Another thing to consider is that if the behaviour is of typeof isn't compatible with decltype for a given compiler it is possible that the typeof extension won't get much development to encompass new language features in the future (meaning it might simply not work with e.g. lambdas). I don't know whether or not that is currently the case, but it is a distinct possibility.
The difference between the two is that decltype always preserves references as part of the information, whereas typeof may not. So...
int a = 1;
int& ra = a;
typeof(a) b = 1; // int
typeof(ra) b2 = 1; // int
decltype(a) b3; // int
decltype(ra) b4 = a; // reference to int
The name typeof was the preferred choice (consistent with sizeof and alignof, and the name already used in extensions), but as you can see in the proposal N1478, concern around compatibility with existing implementations dropping references led them to giving it a distinct name.
"We use the operator name typeof when referring to the mechanism for querying a type of an expression in general. The decltype operator refers to the proposed variant of typeof. ... Some compiler vendors (EDG, Metrowerks, GCC) provide a typeof operator as an extension with reference-dropping semantics. As described in Section 4, this appears to be ideal for expressing the type of variables. On the other hand, the reference-dropping semantics fails to provide a mechanism for exactly expressing the return types of generic functions ... In this proposal, the semantics of the operator that provides information of the type of expressions reflects the declared type. Therefore, we propose the operator to be named decltype."
J. Jarvi, B. Stroustrup, D. Gregor, J. Siek: Decltype and auto. N1478/03-0061.
So it's incorrect to say that decltype completely obviated typeof (if you want reference dropping semantics, then the typeof extension in those compilers still has use), but rather, typeof was largely obviated by it plus auto, which does drop references and replaces uses where typeof was used for variable inference.
p.s. 2023-01-03 C23 (not C++) will evidently officially get typeof in N2927.
For legacy code, I have been using successfully the following:
#include <type_traits>
#define typeof(x) std::remove_reference<decltype((x))>::type
typeof has not been standardized, although it was implemented by several compiler vendors, e.g., GCC. It became obsolete with decltype.
A good explanation for the shortcomings of typeof can be found in this related answer.
Well, typeof is a non-standard GNU C extension that you can use in GNU C++ because GCC allows you to use features from other languages in another (not always though), so they really shouldn't be compared.
Of course other non-standard extensions may exist for other compilers, but GCC is definitely the most widely documented implementation.
To answer the question: it can't be obsolete if it was never a feature.
If you want to compare the merits of either method in C++ then there is semantically no difference unless you're dealing with references. You should use decltype because it is portable and standards conforming.