syntax highlight

Thursday, 27 February 2020

jq: grep and prettify json

If you don't use jq, you are missing a very important utility in your bash toolset. jq let's you query and filter json files from a cli. Just like awk or sed, js's "language" is basically write only, meaning whenever you need to do something there's a 99% chance you'll just be copy-pasting recipes from Stackoverflow until you find the one that works for you. Here are a couple of recipes I found most useful:

cat a json file - with pretty print

jq . /path/to/json_file

Select a single key

jq '.path.to.key'

The command above will return "42" for a json that looks like "{path: {to: {key: 42}}}"

Delete all entries in an object, except for one

jq '.foo|=bar'

The command above will return "{foo: {bar:''}}" for a json that looks like "{foo: {bar:'', baz: ''}}"

This is probably not even enough to get started. Luckily there's plenty of docs to read @ https://stedolan.github.io/jq/manual/

Tuesday, 18 February 2020

Mixin(ish) classes with parameter packs in C++

For some reason I couldn't find many examples of how to use a parameter pack as a mixin, to enable different features with no runtime overhead. Here is a full example of you might implement this (be aware there are some nasal daemons in the code below!). The technique is really based on this one line:

 int dummy[sizeof...(Config)] = { (Config::apply(p), 0)... };

This idiom will unpack a parameter pack and call T::apply, for each T in the parameter pack. You can use this idiom to build very clean mixin-type interfaces with static dispatch, or to build job security.

Full example:

struct EnableFeatureA {
  template <typename T> static void apply(T *a) {
    cout << a->a() << endl;
  }
};

struct EnableFeatureB {
  template <typename T> static void apply(T *a) {
    cout << T::b() << endl;
  }
};

template <typename Impl, typename... Config>
struct Foo {
  Foo(){
    // Call apply() for each type in Config
    Impl *p = nullptr;
    int dummy[sizeof...(Config)] = { (Config::apply(p), 0)... };
  }
};

struct Bar;
using FwdFoo = Foo<Bar, EnableFeatureA, EnableFeatureB>;

struct Bar : FwdFoo {
   int a() { return 4; }
   static int b() { return 2; }
};