The pipe operator as an extension method

Compared to other languages, for example, C# and JavaScript, C++ does not support extension methods, that is, you cannot extend a class locally with a new member function.

For example, you cannot extend std::vector with a contains(T val) function to be used like this:

auto numbers = std::vector<int>{1,2,3,4}; 
auto has_two = numbers.contains(2); 

However, you can overload the pipe operator to achieve this, almost equivalent, syntax:

 auto has_two = numbers | contains(2); 

Get C++ High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.