C++ Concepts

C++(20) Concepts has superseded the functionalities from #202204181611, #202204181536 and #202204182011. It could be defined as follows using concept keyword:

template<typename T>
concept Equality_comparable = requires(T a, T b) {
  { a == b } -> bool; // compare Ts with == which return boolean
  { a != b } -> bool; // compare Ts with != which return boolean
}

It could be used to restrict the type which must matched the defined characteristics. Sort of like 202204061235. We could use it in a template like below:

template<Equality_comparable T>
bool is_zero(T a) {
  return a == 0;
}

If we use it directly, concept will always return boolean. For example:

static_assert(Equality_comparable<int>); // true

struct S { int s; };
static_assert(Equality_comparable<S>); // false
Links to this page
  • Template Deduction Guide

    Template Deduction Guide is used to tell the compiler that the type of the passed parameter(s) should meet the requirement stated by the guide. It usually used alongside with #202204181611. Its replacement will be 202203281200# in C++20.

  • Compile Time Type Determination

    We could decide whether we should execute or enable a section of codes based on circumstances. C++ standard libraries provides various ways to support this prior to C++20. In C++20, there is no need for it because of 202203281200#.

  • C++ Traits

    C++ standard libraries contains type_traits and iterator_traits defined in the libraries <type_traits> and <iterator> respectively. They are used heavily in 202204181536# and 202204182011# but soon deem unnecessary due to the introduction of #202203281200 in C++20.

  • C++ Container

    Standard libraries’ containers usually define value_type and iterator to indicate what type of the value and iterator are stored or used in them. It is advised to follow this convention if a custom container should be used. This could be useful if 202204181536 should be used in the codebase although in C++20, 202203281200 is the better alternative for it.

#cpp