X

曜彤.手记

随记,关于互联网技术、产品与创业

吉 ICP 备10004938号

C++20: The Big Four


C++20 是自 C++17 之后的又一次 C++ 语言标准上的“重大改版”。而 “Big Four” 则是该标准中相较于 C++14 与 C++17 而言的,四个最为重要的新特性。它们分别对应着 Concepts、Ranges、Coroutines 以及 Modules。

Concepts

constexpr size_t DEFAULT_INDEX = 0;

template<typename Vec>
using Scalar = typename std::decay<decltype(Vec()[DEFAULT_INDEX])>::type;

template<typename Vec>
// limit the container value and the existence of the member function.
concept FloatVec = 
  std::floating_point<Scalar<Vec>> &&
  requires(Vec vec) {
    { vec.size() } -> std::integral;
  };

template<FloatVec Vec>
auto norm(const Vec& vec) -> Scalar<Vec> {
  using Size = decltype(vec.size());
  Scalar<Vec> result = 0;
  for (Size i = 0; i < vec.size(); ++i) {
    result += vec[i] * vec[i];
  }
  return std::sqrt(result);
}

struct Point {
  float x;
  float y;
  auto size() const -> int { return 2; }
  auto operator[](size_t i) const -> float {
    return i == 0 ? x : y;
  }
};

int main(int argc, char** argv) {
  std::vector<double> vec = {1, 2, 3};
  std::cout << "norm vec:" << norm(vec) << std::endl;
  Point point {1, 2};
  std::cout << "norm point:" << norm(point) << std::endl;
  return 0;
}

Ranges

int main(int argc, char** argv) {
  std::vector<int> ints {0, 1, 2, 3, 4, 5};
  auto even = [](int i) { return 0 == i % 2; };
  auto square = [](int i) { return i * i; };

  for (int i : ints | std::view::filter(even) | std::view::transform(square)) {  // range adapter;
    std::cout << i << ' ';
  }
  return 0;
}

Modules

// A.cc
module;
import utility;
int foo() {}
int main (int argc, char** argv) {
  std::cout << add(10, 20) << '\n';
  return 0;
}
// B.cc
module;
export module utility;
int foo() {}
namespace utility {
  export auto add (int x, int y) -> int {
    return x + y;
  }
  auto minus (int x, int y) -> int {
    return x - y;
  }
}

Coroutines

(持续更新)



这是文章底线,下面是评论
  暂无评论,欢迎勾搭 :)