100 points · by adamnemecek · 10y ago · 81 comments
Yes, but that's not the real point. You can do that in other ways. Creating a new std::algorithm does that, for example.
The real purpose is letting one function be polymorphic in multiple directions. This is called multiple dispatch. Some languages support this as a built-in feature, but C++ doesn't, so a couple different design patterns were invented to fill in this gap. The Visitor pattern is the most popular and is probably the easiest to work with.
https://en.wikipedia.org/wiki/Multiple_dispatch
That is, it lets you do this:
polymorphicOnThis->doSomething(alsoPolymorphicOnThis);
That is, for each permutation of the two types (polymorphicOnThis and alsoPolymorphicOnThis), you can define new specific behavior.http://eli.thegreenplace.net/2016/a-polyglots-guide-to-multi...
I've seen a lot of implementations of the visitor pattern, and almost all of them used it for single dispatch.
The Visitor Pattern doesn't provide multiple dispatch.
The Visitor Pattern relies on multiple dispatch, and so it provides a form of it to itself.
The Visitor Pattern doesn't go away in a language with multiple dispatch; its boiler plate code is just reduced.
What the Visitor Pattern is about is to bring together the benefits that arise from a cluster of ideas: first class functions, and generic functions.
In the Common Lisp object system, OOP functions are "generic functions" which stand alone and are not tied to classes. If we have a "frobosity" method and a list of objects, we can map that list easily to get every object's frobosity: (mapcar 'frobosity objlist). That is to say, we have visited each object in objlist. Each object has effectively "accepted" a "visit" from the frobosity function.
Now what we might want is instead of using generic function, to use a "funcallable object". let's use mapc instead of mapcar, since we don't need to collect the results into a list. The visitor-object itself can do something useful along those lines:
(mapc visitor-object objlist)
This object carries state and can do useful things, like inquire each object about its frobosity and add them together.since we don't have funcallable objects standard Lisp we can borrow the dispatch kernel of the Visitor Pattern:
(mapc (lambda (list-obj) (accept visitor-object list-obj)) objlist)
I.e. we use a method called accept and then curry it with a lambda to simulate visitor-object being funcallable. This lambda is just using double dispatch, just like the Visitor Pattern uses its two-dispatch simulation of double dispatch.If we have that real double dispatch, it's just more convenient to write the rest of this cruft. It's just a simple, linear bunch of definitions like:
(defmethod accept ((visitor this-class) (obj that-class))
;; handle this-class + that-class combination
)
The double dispatch itself isn't the point of the pattern. The point is to use an object as a function which is mapped over some other objects, and that object does something useful: accumulates some information, pretty-prints, translates the structure to something else, etc.Don't do this anymore! Just delete them:
MyClass& operator=(const MyClass&) = delete;
Private-really-means-deleted was a cool and very useful trick before C++11. So useful, that it was a shame to require secret knowledge and aha moments to use. So they just made it a normal feature of the language. There's also a way to explicitly use the default implementation: MyClass& operator=(const MyClass&) = default;Consider the following class:
class X {
private:
X& (const X&); // not defined
public:
X bar() {
X x = ......;
return x;
}
};
Due to programmer error, an instance of X is returned by value despite the class being noncopyable. The copy constructor being private doesn't help as bar() is a method of X. This will compile and link, despite the copy constructor being undefined. I will leave the reason for this as an exercise for the reader.Come to think of it, the trick to make something private in order to "remove" it is one of these very few areas where C++ makes you pay for something you don't use, so I'm not surprised that there is now a special keyword (well, a repurposed keyword) to address that.
Rather, until every compiler you need to target supported this specific C++11 feature. In other words, it's still a cool and very useful trick ;)
For example on the embedded space many toolchains are still C++98, not even C++03.
But Myers had this aha moment about private constructors in 1988! Since then, this has been covered in countless books, tutorials and coding convention documents.
A newbie still has to read something in order to learn about "= delete". This is not "discoverable" just by experimenting with the language!
Knowing that delete is a keyword, and that there are declarations of the form "specifiers fun-declarator = blurb" you are very unlikely to discover, on your own, that the blurb may be the keyword "delete", and that this actually compiles and has a certain useful effect.
However, the combination of constructors and "private:" is discoverable, as Myers' 1988 aha moment shows. It's a logical combination of independent features.
It's okay for techniques in languages to be discoverable logical combinations of features rather than arbitrary syntax thrown in.
It's also okay for the culture which surrounds a language to have a body of techniques which are carried in that culture, rather than shoehorned into the language parser.
Anyway, declaring a constructor " = delete" isn't the same thing as making it private. If it's private, the code in your class scope can still use it. If you can't trust your class private code to do things correctly, then you're screwed; go join IT and write backup shell scripts. So basically this "= delete" is just another ear growing out of the elbow of C++.
We can create a dummy class which has a private copy constructor that is not implemented:
class noncopyable {
private:
noncopyable(const noncopyable &);
};
then simply make this a data member of a class that you don't wish to be copyable: class whatever {
private:
noncopyable nc;
};
The default copy constructor generated by the C++ compiler performs a member-for-member copy, which involves copying nc. That is not possible, so in effect that copy constructor is defeated, not unlike by "= delete".Alternatively use inheritance to mix this in as a trait:
class whatever : private noncopyable {
// ...
};Is that common among programmers?
It's doesn't hurt either that the libraries available in C++ are really cool.
I find it to be the case with most languages.
> Even template metaprogramming alone is gigantic area of ongoing research -- the stuff you can do with it is mind-bending and unavailable in nearly all other languages.
Your are being a bit hyperbolic. Meta-programming is not necessarily a hard thing to do, but in some languages, like C++ it was made impractical at first. Then, templates introduced some metaprogramming aspects with another layer of Turing-completeness. I can appreciate the usefulness of C++ and how templates contribute to it, though.
> Templates are, after all, one of very very few wholly functional, immutable languages out there.
XSLT too ;-)
> And template instantiation is the underlying force behind many of the modern features like lambdas that allow you to access that power without actually knowing templates well.
Lambdas roamed the earth long before templates.
> ... and if you can accept that you will never know the entire language and can just use those bits that make things easier, it is possible to have a healthy relationship with the language.
Agree.
I'm talking about C++ lambdas, in particular, which are templates under the hood.
Um, no. C++ can be safer than C (which is an incredibly low bar) but only if you carefully constrain yourself to certain subsets of the language, which is why the web is chock-a-block with byzantine "C++ coding standards" documents describing all the rules you have to follow in order to avoid shooting yourself in the foot.
"Avoid the parts you don't like" works best for one programmer working alone.
I'm curious which subsets are included in this?
As a developer responsible for understanding what everyone else is doing on the same project, no I cannot accept that.
Dislike Objective-C verbosity and C roots, although I kind of like its Smalltalk influence.
Really strongly dislike C and the culture of insecure software it has brought into our industry.
The majority of C++ programmers make use of:
- RAII
- String classes instead of char* überall
- Vector classes instead of char* überall
- new and delete instead of malloc()/free() and casts
- References for out parameters instead of pointers
- Real enums, specially since C++11, instead of #define
- Smart pointers for memory management
- Type based programming to reduce errors
- Minimize the use of the pre-processor to #include and macros, only when they cannot be expressed via templates, const, constexpr and inline.
Most of the unsafe C++ code is written by the "C with C++" sub-community that are mostly C refugees forced to use a C++ compiler.
Also while the C++ community is pushing for safety with activities like the C++ Core Guidelines and reducing the amount of UB in the standard, the C standard community doesn't care at all.
The only thing that the C community has done regarding security was the Annex K in C99, which was proven so good that it became an optional feature in C11.
RAII and scope based construction/destruction is actually quite nice.
This is a problem with vocabulary types. C tends to do a good job of providing them. C++ tends not to, though there has been some progress in the standard lately in defining classes like unique_ptr and string_view.
C tends to fall down by providing raw memory (an int and a char) to represent fairly subtle relationships (the int represents the size of the string pointed to by the char... what happens when the int is negative?). So C libraries don't 'reinvent the whole stack', but this sort of bookkeeping logic tends to cause bugs (at least security bugs).
...but I get confused by the people who do that, and then turn around to embrace C, the circus where people juggling the chainsaws of "faking templates with macros", "terrible build times", "yet more security vulnerabilities resulting from undefined behavior", "no C-standard defined threading / async support until C1X", and more.
It's common, but I don't get it.
I find it extremely frustrating when I have to use either language in an area that it wasn't designed for.
// file: A.h
class A {
B* _b;
};
// file: B.h
class B {
A* _a;
};
I mean a pointer has a fixed size, so couldn't the compiler just leave some sort of type placeholder in class A until class B is eventually defined. // Things.h
namespace Foo { class A { C* c; }; }
namespace Bar { class B { C* c; }; }
Are A::c and B::c the same type? // TU1.cpp
class C {};
Were you right? // TU2.cpp
namespace Foo { class C {}; }
namespace Bar { class C {}; }
What about now? // TU3.cpp
class C {};
namespace Foo { class C {}; }
namespace Bar { class C {}; }
This may get you shot, but is legal. What about now?Ahh - all three are in the same program. Just pretend they #included <c.h>, <foo/c.h>, and <bar/c.h>. Having A::c's type be different in different contexts is a violation of the "One Definition Rule", for which the punishment is undefined behavior.
Although you can still recreate the above scenarios by just #including <Things.h> after <c.h> and company, but you're a bit more likely to have Things.h #include what it needs to clarify the situation. Hopefully. So maybe we can get away with it!
void foo() { D * d; }
Is that a pointer definition or invoking operator* against two globals? void bar() { E < 42 > e; }
Now you're just fucking with me. Is that some comparison operators or a template? void baz() { F < (42) > f; }
That didn't clarify anything. Stop it. void he_comes() { G < (42) > g(); }
What do you mean I just declared a function? Stop it! v̹̊̈́̇ͦ̌ͭ͂ͅo̅̉̀ͪ̚ī̵̠̘̋d̸͚̪̝̹͙͆͛̿ ͉̜̳ͪͬ́ͣ̌ẑ̸̹̹̩̩a̡̰ͣͭ̄͒ͫ̇̚l̛̹̫͓̣͖͈̐ͬg̢͕̘͙o̪͆̏ͥ͟(̖̭̟̱̰ͩ)̘̬͉̺̉̓ ̦͆́̚{ ̶̪͙̹͈ͮͧ̋ͪͤͅĜ͔̙̉͢ ̝̯ͭ̈́͘<̨͊̂͋̎ ̤͇̼̝͔͇ͯ̑̋ͫ̾͐̚(ͨͪͦ̈̈́ͥ4͍͗̆2̲̞̦̳̖͡)͖͇̟̥ͮ͘ ̺̖͙̘̳͛̐̊͊>̼͍̘̦͖̎ ̧̘̻̭͉̺g̟͓̑ͦ̌̃(̪ͬͪͤ̎̉͘ȉ̮̥͖́n̸̝̪̗̯͇̓̈́̀̔̄̍́t͓̟͍ͨͪ(̰͈̻͎̣͉̀̿̈͑)̝͚̆̃̇)̠̃;̺͎̙̰̈́̏̚͘ ̶̜͍̠̼ͬ}̡̤̰̮̳͈̌͛ͤ̈́
A function accepting a function pointer? Stooooop! // file: A.h
class B;
class A {
B* _b; // or any of the other variants.
}; class A {
class B* _b;
}; // file: A.h
class B;
class A {
B* _b;
};
// file: B.h
class B {
A* _a;
}; class B;
class A {
B* _b;
};
and it'll be happy."But it has garbage collection" they said. "You dont have to worry about pesky memory managment, the language has an intelligent VM that handles it for you!".