=> isn't overloadable in C++. I have always wondered whether this is just a pure coincidence or whether there is a specific reason this sequence of two characters cannot be overloaded. The emergence of the comparison operator <=> leads me to believe the former.
I think it's a prime candidate for overloading because it looks like an arrow, which is very common in functional programming syntax and mathematics. Granted -> exists already but having another arrow could be useful to disambiguate between the two. I also don't see how it could break backwards compatibility.
C++ only allows you to overload operators that are already operators in the base language.
The base language defined operators, each with its associated precedence and associativity. In an operator overload, you can supply the meaning of that operator (the code that will be executed) for types for a user-defined type (or sometimes, for a combination of two user-defined types).
You cannot, however, just choose an arbitrary set of symbols, and treat it as an operator (no matter how attractive that might be).
There are languages that do allow this--for example, ML (and many of its descendants) allow you to define an operator with an entirely new name that's not part of the base language at all. When you do this, you define the precedence and associativity you want that operator to have. I think that's great, and provides a useful capability--but (at least as the capability is defined in ML) it also has some weaknesses that probably wouldn't fit nearly so well with how things work in C++. I wouldn't expect to see it as part of C++ any time soon (or, probably, ever).
In C++, “overloading” is a mechanism for providing a custom definition for existing operators so they can be used in custom types, not a mechanism for adding new operators to the language. You can’t change the meaning of a “=>” operator because C++ (as of this writing at least) doesn’t have a “=>” operator.
As a supplement to Jerry’s great answer, I want to point out that this was not an oversight by any stretch, but a very conscious design decision. Bjarne Stroustrup, the original creator of the C++ language, describes his thoughts on this in his fabulous book “The Design and Evolution of C++”, as I quote here:
I [Stroustrup] considered it important to provide overloading as a mechanism for extending the language and not for mutating it; that is, it is possible to define operators to work on user-defined types (classes), but not to change the meaning of operators on built-in types. In addition, I didn’t want to allow programmers to introduce new operators. I feared cryptic notation and having to adopt complicated parsing strategies like those needed for Algol68.”
(bold emphasis mine, italics in the original)
Source: Stroustrup, Bjarne: “The Design and Evolution of C++”, Addison-Wesley, 1994. §3.6.5
PS: Although a bit dated as a reference for modern C++ design, this is an excellent and fascinating source to explore the history and the reasoning that led to the design of the original C++ language. The language further design has long been under the purview of an ISO Standards committee but its continuous evolution has continued to be driven by many of the same principles described in the book and Dr. Stroustrup continues to be an important voice in that evolution process.
Related
In C++17, mathematical special functions (such as Bessel functions, for example) were added to the standard and are already relatively well supported by modern compilers.
However, those functions are defined for real-valued arguments, while some applications in computational physics heavily use their complex equivalents.
I wonder if
there is/were any technical specifications/proposals for enhancing std::complex<> with special functions (I was not able to find anything related)
if such a proposal is in the active state and has a chance for, I guess, C++23
there are considerations against including special math functions for std::complex<> besides their [relatively] narrow use
I know of no such proposal currently under review.
I would expect such a proposal to come through SG6 (the numerics study group).
I am wondering what is the origin of move semantics in C++? In particular was it invented specifically for this language or there was something similar in other language(s)? In the latter case could you give some references.
There doesn't appear to be any kind of specific ancestor to the concept. The origin of C++'s move semantics, as noted in the original proposal, was discussion in newsgroups:
Move semantics in various forms has been discussed in C++ forums (most
notably comp.lang.c++.moderated) for years.
To my mind, they are tightly coupled with C++'s notion of lvalues and rvalues which, if I'm not mistaken, is purely a C++ concept. A language that doesn't have lvalues, rvalues and their new C++11 friends doesn't need move semantics in the way that C++ implements them.
More generally, though, the concept of moving stuff around rather than copying is just a fundamental concept. Whenever you write a linked list and you "swap elements" by actually just swapping pointers to them, you're doing a "move". Basically.
You can read "A Proposal to Add Move Semantics Support to the C++ Language" to get more information on the motivation behind the concept, as well as why this needs to have direct language support rather than being implemented using library facilities.
i'm wondering if C++0x (C++11) (with lambdas and perfect forwarding) is (a superset of) a functional language.
is there any feature of functional languages, that C++ doesn't have?
The functional programming paradigm models computation as a relation between sets, and is thus inherently declarative. However, in practice, we often think of functions as imperative, ie you put in an input value and get out an output value, same as with a procedure. From this point of view, the characteristic property of a function is that it has no side-effects. Because of ambiguity of the terms, we call such a function pure, and a language which only has pure functions would be a purely functional language.
However, not all functional languages are pure: A functional language is a language with syntax and semantics which allows the programmer to use the functional paradigm efficiently. Some of the concepts which make using the paradigm feasible include - among others - lambda expressions with lexical closure, higher-order functions, variant types and pattern matching, lazy evaluation, type-inference (in case of statically-typed languages).
This is by no means an authorative list, and a language can very well be functional without providing all or even most of them, but if a language does - ie makes them usable without having to jump through major hoops - their presence is a strong indicator that the language should be considered functional.
I don't know enough about Boost to decide whether or not C++03 + Boost is a viable functional language, but C++0x definitely makes C++ more functional, perhaps even pushing it over the subjective boundary of the realm of functional languages.
As an aside, the same considerations apply to other programming paradigms: C++ is also not a purely object-oriented language (indeed, it's very hard - perhaps even theoretically impossible - to design a language which is both purely functional and purely object-oriented), and most features one commonly associates with OO-languages (classes, inheritance, encapsulation) are actually in no way authorative as well...
Check out the list of Functional Programming Languages definitions and discussion on the C2 wiki.
Some of the most common (and least disputed features) are:
First class functions - function class represents first class functions.
Higher Order Functions - Can be emulated with function objects.
Lexical Closures - Can be emulated with classes.
Single Assignment - More of a convention. You can do this by declaring all variables const.
Lazy Evaluation - Can be achieved with TMP
Garbage Collection - still missing. Pretty much necessary in a functional language, since lifetime and scope are not the same, as #Pascal pointed out in the comments above.
Type Inference - auto
Tail Call Optimization - Not strictly necessary for a functional language, but compiler dependent in C++.
I think or is keyword in c++.
It might be that I've been doing too much python code recently but I find or is more readable than || and xor much more readable than ^.
Is it a good idea to use the word alternatives to the symbolic operators?
Why don't I see them used more?
The unsatisfying answer is that you should use symbolic operators because everyone else does.
An arguably more sensible reason is that they stand out more from the rest of the code.
Is it a good idea to use the word alternatives to the symbolic operators?
Completely depends on the target audience for your code – both people and tools. People can be unused to them, and some tools don't recognize them. (Sometimes those tools use <ciso646> to define them as macros.)
I've started to use "and" and "or" more, especially when switching between C++ and Python, and it has been more readable. The bit of extra consistency between languages matters more than I first thought it would, but more importantly, && and || are control structures and not operators (i.e. short-circuiting), thus making them words differentiates from operators.
(Yes, technically they're operators in C++, but they're more similar to if, else, return, while, and so forth than +, -, *, and other operators. The comma and conditional operators are similarly control structures, and it probably isn't a coincidence they are often found confusing, or at least less readable than separate statements and if/else, respectively.)
However, I very rarely use them in new code written for SO, for example, because I've not yet encountered a question where bringing up this side issue was more important than being readable to SO's C++ audience.
Every C++ programmer knows about && and ||.
Not every C++ programmer is aware that and and or are legal alternatives.
For that reason alone, you're better off sticking with what's commonly used.
It is pretty easy to get used to, so I'd say it's not a big deal, and definitely not worth potentially confusing the reader of your code over.
These keywords are alternative tokens which were added to the standard (Standard C) in 1995. See details here
https://en.wikipedia.org/wiki/C_alternative_tokens
Why the keywords were added:
The alternative tokens allow programmers to use C language bitwise and logical operators which could otherwise be hard to type on some international and non-QWERTY keyboards.
How they were added:
They are implemented as a group of macro constants in the C standard library in the iso646.h header.
The iso646.h header defines 11 macros including or.
What about C++:
The above-mentioned identifiers are operator keywords in the ISO C++ programming language and do not require the inclusion of a header file. For consistency, the C++98 standard provides the header <ciso646>. However the latter file has no effect, being empty.
So, there is a historic reason for having the keywords in C/C++ languages, and it is not related to what is better to use. As mentioned above, you should stick to a coding convention.
My first question is or a bit-wise or | or a Boolean shortcut or ||?
I bet there is half a dozen people on my team that would have to go look it up.
So I think it is better to stick with the standard convention,
Because that is what people are used to. The whole point of programming is to not be ambiguous.
These keywords are only there for terminals that can't handle the special characters |, & etc. Whether they constitute a more readable code or not is arguable.
If you know what || means then or is not more readable than ||. And if you know the very fundamentals of C++, i.e. the syntax, then in my humble opinion one is not more readable than the other.
Also, C++ programmers in most cases use the special-character alternatives of the keywords. So it's usually a good idea not to be the exception in a project, unless you're starting a project and you're setting the rules.
|| is how you say "boolean or" in C++. If you actually write or you are going to confuse the heck out of readers of your code, even if you can get the compiler to accept it.
I really do have sympathy for your argument, deft. Honestly. C++ code is really ugly (and IMHO hard to follow) due to its reliance on line-noise-like symbology. But that's the C++ philosophy. If you want nice Englishy reable code, C++ is just not your language. Try Ada.
I'm serious here. In a lot of ways Ada is a better language. This is one of them. But if you are going to stick with C++ instead, you need to ebrace it. Trying to write Ada (or Pascal) in C++ is no better than trying to write C++ or Fortran in Ada.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
As you may have heard, the last meeting of the C++ standards committee voted to remove concepts from the next C++ standard. Of course, this will affect other features and would seem to throw the standard wide open again. If that is the case, which other features do you think should be stripped away (or added), and why?
Links:
Removal of Concepts -- Danny Kalev (on the decision to remove concepts)
Simplifying the use of Concepts -- Bjarne Stroustrup (on the problems with concepts as they look now)
The Long Pole Gets Longer -- Martin Tasker (on the impact to the schedule for C++0x if concepts have to be fixed)
The C++0x "Remove Concepts" Decision - Stroustrup on the issue on Dr. Dobbs
Trip Report: Exit Concepts, Final ISO C++ Draft in ~18 Months - Herb Sutter
Concepts Get Voted Off The C++0x Island - Jeremy Siek defending the current Concepts spec
What Happened in Frankfurt? - Doug Gregor on C++Next (on the history and removal of Concepts).
Of course, this will affect other
features and would seem to throw the
standard wide open again.
Hardly. They still want to wrap up the standard soon, which is one of the main reasons for removing concepts. Making it "wide open" to unrelated changes would just throw away everything they gained by ditching concepts.
Anyway.... Of the remaining C++0x additions, I can't think of anything else I'd want to remove. I agree with their decision regarding concepts though. Stroustrup's paper really outlined some serious problems, The current specification for concepts would admittedly simplify template error messages, but it would do so by dramatically reducing the usefulness of generic programming -- a price I'm not willing to pay.
When I first read that paper, it scared me, because I assumed it was too late in the process for making serious changes to the spec. Turns out it wasn't, and the committee was willing to take dramatic action.
But apart from this, I think C++0x is in good shape. The remaining new features all look worthwhile.
Of course, there are plenty of existing features I'd love to remove. Primarily the vector<bool> specialization. There are other popular examples of features that didn't work out (the export keyword, exception specifications), but the vector specialization is the only one of them that can't be ignored. As long as we don't try to export templates, it doesn't matter that the keyword exists (and isn't implemented by compilers), and we can just refrain from using exception specs, but every time we need a vector of bools, we're bitten by the stupid premature optimization that slipped into the current standard.
Unfortunately, it seems like they've given up on removing it. (Last I checked, it wasn't even deprecated).
Of course, plenty of old C cruft could be ditched too, but recently, I've discovered that the one change I'd really love to see is...... ditching the Iostreams library. Toss it out, and build a new STL-style I/O library based on generic programming.
The current OOP-styled Iostreams library is ugly, slow, overcomplicated and inflexible. There's too much voodoo involved in defining new streams, too few standard stream types involved, too little flexibility (the problem that made me realize how limited the library is, was that I needed to extract a float from a string. Easy to do with stringstream, but if you need to do it often, you don't want to have to copy the input string every time (as the stringstream does) -- where's the stream that works on an existing iterator range? Or a raw array, even?)
Throw IOstreams out, develop a modern replacement, and C++ will be vastly improved.
And perhaps do something about the string class as well. It works sort of ok'ish as it is now, but really, what's with the huge number of member functions? Most of them would work better, and be more general, as free functions. Too much of the standard library relies specifically on the string class, when it could in principle work with any container, or even an iterator (std::getline, I'm looking at you)
Personally, I want C++ to finally break away from C. No more pre-processor, no more header files. I basically want D, but without all the stuff that D tacks on, using the STL.
None, I think the rest of the draft was great - a large number of very small pieces that can be correctly implemented independently, allowing vendors to evolve toward complete support and allowing users to take a "shopping list" approach.
Quite a different situation with contracts, as they were like a whole new parallel type system and would have been very likely to have led to different compilers ending up with their own backward compatibility problems, very similar to CSS in web browsers.
There are two things I think should be added to C++0x, I've thought of both these myself and then found that others have suggested them before but it doesn't seem like they're going to happen.
1. Defaulting Move Constructors and Move Assignment Operators
Writing a move constructor is a manual and error prone activity, if a member is added it must be added to the move constructor and assignment operators and std::move must be used religiously. That's why I think these functions should be defaultable.
movable(movable&&) = default;
movable& operator=(movable&&) = default;
Edit (2009-10-01): Looks like this is going to happen after all.
2. Override Type Deduction for Expression Templates
Expression templates often define types that should not be used directly, a case in point is the return value of std::vector<bool> operator[](size_type n), if auto or decltype are used on this kind of object unexpected behaviour may ensue.
Therefore a type should be able to say what type it should be deduced to be (or prevent deduction using = delete syntax).
Example for vector addition.
// lazy evaluation of vector addition
template<typename T, class V1, class V2>
class vector_add {
V1& lhs_;
V2& rhs_;
public:
T operator[](size_t n) const
{ return lhs_[n] + rhs_[n]; }
// If used by auto or decltype perform eager creation of vector
std::vector<T> operator auto() const
{
if (lhs_.size() != rhs_.size())
throw std::exception("Vectors aren't same size");
std::vector<T> vec;
vec.reserve(lhs_.size());
for (int i = 0; i < lhs_.size(); ++i)
vec.push_back(lhs_[i] + rhs_[i]);
return vec;
}
To me the problem is not what other features should be stripped away, but how complex will other features be after concepts have been removed. That and how much longer will it take for the rest of the features to be rephrased without concepts.
A lot of features assumed that concepts would be accepted into the language and the wording is expressed in terms of concepts. (I wonder if any proposed feature depends on concepts).
I also wonder how other libraries will evolve (think boost::type_traits) to take the niche left by concepts. Part of what concepts provided can be implemented (even if in a more cumbersome way) in terms of traits applied to the type arguments.
To me, the most important thing that concepts added to the language was an expressive formulation of compilation errors, which is nowadays one of the places where C++ is most criticized.
R.I.P. concepts.
Do whatever you want with concepts, but for god's sake keep threads and atomics, we absolutely need them. Perhaps add thread groups and support for cooperative threads a.k.a. fibers. IMO these are far more important than concepts, because everyone uses/will soon be using threads.
I'd like to remove =delete.
There's already a common and accepted idiom for acheiving the same effect (declare the function in question as private). I think this feature will just generate lots of 'I used =delete to remove a base class function from my derived class, but it can still be called using a base class pointer' questions.
Not to mention confusing people between the (now) two meanings of the delete keyword.
Strip away the pages of error messages on template code!
IIRC concepts should solve a big C++ coder problem: Human readable error messages for the STL. Its bad news that this issue isn't addressed.
The un-named function / lambda function stuff makes me nervous. Function objects are perfectly good and are explicit, thus easier to read and find.
On the other hand I kinda liked concepts, though I certainly would not have used them every day.