Daniel Lemire's blog

, 3 min read

Book Review : Template Metaprogramming with C++

3 thoughts on “Book Review : Template Metaprogramming with C++”

  1. Denis says:

    “Up until recently, you could not mix templates and lambdas, but now you can with C++20:”

    You could since C++14.

    int g(int x, int y) {
    auto lambda = [](auto x, auto y) { return x + y; };
    return lambda(x, y);
    }

    It’s the same as
    https://godbolt.org/z/f59cezsje

    1. Jonathan O'Connor says:

      I think the change in C++20 was to make it easier to get the type of x and y. Before C++20, you’d need the following code:

      int g(int x, int y) {
      auto lambda = [](auto x, auto y) {
      using T = decltype(x);
      return T(x + y);
      };
      return lambda(x, y);
      }

      C++20 allows the following:

      int g(int x, int y) {
      auto lambda = [](T x, T y) {
      return T(x + y);
      };
      return lambda(x, y);
      }

      This last example also ensures that x and y have the same type, which the C++14 example does not.

  2. Denis says:

    “Up until recently, you could not mix templates and lambdas, but now you can with C++20:”

    You could since C++14.

    int g(int x, int y) {
    auto lambda = [](auto x, auto y) { return x + y; };
    return lambda(x, y);
    }

    It’s the same as

    [](T1 x, T2 y) { return x + y; };

    however, hence the C++20 syntax.
    https://godbolt.org/z/f59cezsje