Home My First Moment of C++ Nirvana
Post
Cancel

My First Moment of C++ Nirvana

 Preview Image

I make my living working with web scripting languages. In my free time however I’ve been in an eccentric orbit with C++ for years, periodically diving deep into the STL gravity well, basking in the glow of the low level control and the bewildering array of semantic options, until some hangup flings me back outward, narrowly escaping immolation.

Starting with C++11, I began to think maybe this is something I could work into a micro-service, and not hate myself. Smart pointers, type inference and lambdas were the first features that made me tell people “You should check out (modern) C++, there is some cool stuff happening”. Now with C++17 finalized and compilers getting closer to the standard every day, I’m super excited about what’s next.

Previously my experience with C++ has been mashing my programs against clang until the types line up correctly and something compiled. I was eventually able to get something out, but it wasn’t a pleasant encounter. Recently, however, I had my very first moment of C++ nirvana. I’ve had this happen in other languages, where an intuitive application of some part of the language “just works” when applied in some other context. (Un)marshalling json strings in/out of nested Go structs comes to mind. Until now, this had eluded me with C++. The moment came when I tried using a struct initializer as a function param. Below is a simple outline of the situation:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
struct coord {
  int i = 0;
  int j = 0
}
void printCoord (const &coord position) {
  std::cout << position.i << " " << position.j
}
int main () {
  auto c = coor{0, 1};
  printCoord(c); // print coord
  printCoord({0, 1}); // WORKS!... on c++14 and above
}

In the body of the main function you can see the difference, before C++14 the struct has to be initialized and passed as an argument separately, but in the newer spec, the initializer can be used as a parameter. This is visually similar to using object literals in JavaScript (especially w/ structuring in es6).

There are still a few features I’d like to see implemented for C++ (modules, and reflection especially), but I feel that right now, it’s on the right track to compete with new languages for mind-share.

-->