Sep 23, 2025

[C++][Cppcon 2025] Concept-based Generic Programming - Bjarne Stroustrup

Reference:
Concept-based Generic Programming - Bjarne Stroustrup - CppCon 2025

Concepts are functions

OOP

  • Focused on defining type of objects, often in class hierarchies
  • Applies to one object at a time
  • Relies on name equivalence
  • Run-time selection among an open set of types
  • Inlining is difficult (typically impossible)
  • Defining an interface requires precisely specifying types
    requires significant foresight, conceptually and in technical details.

GP

  •  Focused on a functions' requirements on its arguments
  •  Often involving relationships among multiple arguments
  •  Relies on use patterns (a generalization of structural equivalence)
  •  Compile-time selection among types in scope
  •  Inlining is easy
  •  Doesn't offer interfaces in the ABI sense
        Use OOP for that

Concepts can be partial constraints

We can't always get first shot perfect. Needs several iterations.


Concept can take value arguments

not just type arguments(same as template, i.e. non-type arguments)


Concepts are not just for template arguments


Concept type matching


Definition checking





e.g.
consteval bool is_power_of_two(int n) {
  if (n == 0) return false;
  while ((n&1) == 0) {
    n >>= 1;
  }
  return (n==1);
}


template<int S> concept buffer_space = (1024 <= S) && is_power_of_two(S);

template<typename T, int S>
  requires buffer_space<S>
struct Buffer {
  T buf[S];
};


void test0() {
  Buffer<char, 100> b1; // error, too small.
  Buffer<char, 10000> b2; // error, not binary
  Buffer<int, 2048> b3; // ok
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.