DEV Community

Troels F. Rønnow
Troels F. Rønnow

Posted on

The delights of C++17

Over the years, I've made a ton of C++ experiments to understand new language features. Yesterday, I was looking for a specific example I wrote a few years back.

I didn't find it, but I did find this gem that adds additional syntax:

#include "new-syntax.hpp"

int main() {

  let [a, b, c] be {42, 3.14, "Hi!"} exec {
    print "a = ", a;
    print "b = ", b;
    print "c = ", c;
  }

  return 0;
}
Enter fullscreen mode Exit fullscreen mode

To my surprise, it compiled and ran. The key functionality it makes use of is the C++17 template deductions expressed through a couple of macros in new-syntax.hpp:

#pragma once
#include <iostream>
#include <tuple>
#include <vector>
#include <tuple>

struct Print {
  Print(std::ostream &s): s(s) {}
  template<class T> Print &operator,(T &&t) { return s << t, *this; }
  ~Print() { s << '\n'; }
private:
  std::ostream &s;
};

#define print Print(std::cout),

#define let for(auto &&
#define be : {std::tuple
#define exec })
Enter fullscreen mode Exit fullscreen mode

Not sure that it is particularly useful, but C++ never fails at amazing me with how flexible it has become over the years while remaining statically typed.

Top comments (0)