// Minimal single-threaded model of C9-style cancellation.
//
// Key difference from the stop_token version: a cancelled coroutine is NEVER
// resumed. The cancel callback destroys every frame of the logical thread
// (leaf -> entry), running destructors, and then resumes an "on_exit" handle
// so the owner learns the thread is gone. No code checks a token.
//
// Name map to google3/util/c9/internal:
// PromiseLink -> CoroutinePromiseLink (waiter link, co_thread)
// CoThread -> CoThread (cancelled_ AsyncNotification, on_exit)
// SuspensionToken -> SuspensionToken (BecameReady/Cancelled/AlreadyCancelled,
// DestroyCallStack)
// Scheduler -> ThreadState ready queue + Schedule/CancelWaiter
// Yield / CondVar -> leaf awaitables like c9::Event::Awaitable
#include <algorithm>
#include <coroutine>
#include <deque>
#include <exception>
#include <functional>
#include <iostream>
#include <optional>
#include <type_traits>
#include <utility>
struct FrameCounter {
static inline int live = 0;
FrameCounter() { ++live; }
~FrameCounter() { --live; }
};
class CoThread;
// Base of every Co<T> promise. The `waiter` pointers form the intrusive
// "coroutine call stack" that cancellation walks and destroys.
struct PromiseLink {
std::coroutine_handle<> self; // this frame
PromiseLink* waiter = nullptr; // caller frame; nullptr for the entry frame
CoThread* co_thread = nullptr; // logical thread this frame belongs to
};
// One logical thread of execution = one chain of nested co_awaits.
class CoThread {
public:
explicit CoThread(std::coroutine_handle<> on_exit) : on_exit_(on_exit) {}
std::coroutine_handle<> on_exit() const { return on_exit_; }
// Called by the leaf awaitable while suspending. False = already cancelled,
// so the leaf must not park; it must destroy the stack instead.
bool Register(std::function<void()> on_cancel) {
if (cancelled_) return false;
on_cancel_ = std::move(on_cancel);
return true;
}
void Unregister() { on_cancel_ = nullptr; }
// Request cancellation. If a leaf is parked, its callback runs now and
// destroys the whole chain. If the chain is currently running, nothing
// happens here; it dies at its next suspension point (Register -> false).
void Cancel() {
cancelled_ = true;
if (on_cancel_) std::exchange(on_cancel_, nullptr)();
}
private:
std::coroutine_handle<> on_exit_;
bool cancelled_ = false;
std::function<void()> on_cancel_;
};
// Handed to a leaf awaitable at suspension. Exactly one of BecameReady,
// Cancelled, AlreadyCancelled is called for each suspension.
class SuspensionToken {
public:
explicit SuspensionToken(PromiseLink* leaf) : leaf_(leaf) {}
bool operator==(const SuspensionToken&) const = default;
bool RegisterForCancellation(std::function<void()> on_cancel) {
return co_thread().Register(std::move(on_cancel));
}
// Normal wakeup: stop listening for cancel; caller resumes the leaf.
std::coroutine_handle<> BecameReady() {
co_thread().Unregister();
return leaf_->self;
}
// Cancel callback won the race: destroy the chain, tell the owner. The leaf
// coroutine is never resumed.
void Cancelled() {
std::coroutine_handle<> on_exit = co_thread().on_exit(); // read first
DestroyCallStack(); // frees leaf_
on_exit.resume();
}
// Register failed (cancelled before we could park): destroy the chain and
// return on_exit for the caller to symmetric-transfer into.
std::coroutine_handle<> AlreadyCancelled() {
std::coroutine_handle<> on_exit = co_thread().on_exit();
DestroyCallStack();
return on_exit;
}
private:
CoThread& co_thread() { return *leaf_->co_thread; }
// Callee before caller, iteratively, so OS stack depth stays O(1).
void DestroyCallStack() {
for (PromiseLink* p = leaf_; p != nullptr;) {
PromiseLink* next = p->waiter;
p->self.destroy(); // runs this frame's destructors (RAII)
p = next;
}
}
PromiseLink* leaf_;
};
// Ready queue of wakeups. Holds tokens, not raw handles, so BecameReady runs
// (unregistering the cancel callback) right before resume.
class Scheduler {
public:
void Schedule(SuspensionToken t) { ready_.push_back(t); }
// Pull a scheduled wakeup back out so the frame can be destroyed instead.
// False = already dequeued and running; cancellation then takes effect at
// the coroutine's next suspension point.
bool CancelWaiter(const SuspensionToken& t) {
return std::erase(ready_, t) > 0;
}
void Run() {
while (!ready_.empty()) {
SuspensionToken t = ready_.front();
ready_.pop_front();
t.BecameReady().resume();
}
}
private:
std::deque<SuspensionToken> ready_;
};
// Awaitable child coroutine. Lazy start, symmetric transfer, frame destroys
// itself at final_suspend (result is written into the parent's frame first).
template <typename T>
class Co {
static constexpr bool kVoid = std::is_void_v<T>;
struct Empty {};
using Slot = std::conditional_t<kVoid, Empty, std::optional<T>>;
template <typename U>
struct ReturnValue {
std::optional<U>* result = nullptr; // lives in the awaiting parent
void return_value(U v) { result->emplace(std::move(v)); }
};
struct ReturnVoid {
void return_void() {}
};
public:
struct promise_type
: PromiseLink,
FrameCounter,
std::conditional_t<kVoid, ReturnVoid, ReturnValue<T>> {
Co get_return_object() {
auto h = std::coroutine_handle<promise_type>::from_promise(*this);
this->self = h;
return Co(h);
}
std::suspend_always initial_suspend() noexcept { return {}; }
auto final_suspend() noexcept {
struct Final {
bool await_ready() noexcept { return false; }
std::coroutine_handle<> await_suspend(
std::coroutine_handle<promise_type> h) noexcept {
PromiseLink* waiter = h.promise().waiter;
std::coroutine_handle<> on_exit = h.promise().co_thread->on_exit();
h.destroy(); // frame gone; only locals used from here on
return waiter != nullptr ? waiter->self : on_exit;
}
void await_resume() noexcept {}
};
return Final{};
}
void unhandled_exception() { std::terminate(); }
};
explicit Co(std::coroutine_handle<promise_type> h) : h_(h) {}
Co(Co&& o) noexcept : h_(std::exchange(o.h_, {})) {}
~Co() {
if (h_) h_.destroy(); // only if never started
}
bool await_ready() const noexcept { return false; }
template <typename P>
std::coroutine_handle<> await_suspend(std::coroutine_handle<P> parent) {
promise_type& p = h_.promise();
p.waiter = &parent.promise();
p.co_thread = parent.promise().co_thread;
if constexpr (!kVoid) p.result = &result_;
return std::exchange(h_, {}); // frame now owns itself
}
T await_resume() {
if constexpr (!kVoid) return std::move(*result_);
}
// For bridges only: hand the entry frame to a new CoThread.
std::coroutine_handle<promise_type> Release() {
return std::exchange(h_, {});
}
private:
std::coroutine_handle<promise_type> h_;
Slot result_;
};
// Tiny coroutine used as a CoThread's on_exit handle.
struct OnExit {
struct promise_type : FrameCounter {
OnExit get_return_object() {
return {std::coroutine_handle<promise_type>::from_promise(*this)};
}
std::suspend_always initial_suspend() noexcept { return {}; }
std::suspend_never final_suspend() noexcept { return {}; }
void return_void() {}
void unhandled_exception() { std::terminate(); }
};
std::coroutine_handle<> handle;
};
OnExit ReportExit(const char* name) {
std::cout << name << ": thread exited\n";
co_return;
}
// Bridge: start `co` as the entry frame of a fresh CoThread (what C9 bridges,
// RunConcurrently and WithDeadline do for their children).
void Spawn(Scheduler& sched, CoThread& ct, Co<void> co) {
auto h = co.Release();
h.promise().co_thread = &ct; // waiter stays nullptr: entry frame
sched.Schedule(SuspensionToken(&h.promise()));
}
// ---- Leaf awaitables (the only place cancellation is "implemented") ----
// Re-queue the current coroutine (simulates work). Cancellable.
class Yield {
public:
explicit Yield(Scheduler& s) : sched_(s) {}
bool await_ready() const noexcept { return false; }
template <typename P>
std::coroutine_handle<> await_suspend(std::coroutine_handle<P> h) {
token_.emplace(&h.promise());
if (!token_->RegisterForCancellation([this] { Cancel(); })) {
return token_->AlreadyCancelled();
}
sched_.Schedule(*token_);
return std::noop_coroutine();
}
void await_resume() const noexcept {}
private:
void Cancel() {
// Copy out: Cancelled() destroys the frame that holds *this.
Scheduler& sched = sched_;
SuspensionToken token = *token_;
if (sched.CancelWaiter(token)) token.Cancelled();
}
Scheduler& sched_;
std::optional<SuspensionToken> token_;
};
// Condition variable. Note Wait() takes no token: cancellation is implicit.
class CondVar {
public:
explicit CondVar(Scheduler& sched) : sched_(sched) {}
class Awaiter {
public:
explicit Awaiter(CondVar& cv) : cv_(cv) {}
bool await_ready() const noexcept { return false; }
template <typename P>
std::coroutine_handle<> await_suspend(std::coroutine_handle<P> h) {
token_.emplace(&h.promise());
if (!token_->RegisterForCancellation([this] { Cancel(); })) {
return token_->AlreadyCancelled();
}
cv_.waiters_.push_back(*token_);
return std::noop_coroutine();
}
void await_resume() const noexcept {}
private:
void Cancel() {
CondVar& cv = cv_;
SuspensionToken token = *token_;
// Either still parked here, or NotifyOne already moved it to the ready
// queue. Pull it back from wherever it is, then destroy.
if (std::erase(cv.waiters_, token) > 0 || cv.sched_.CancelWaiter(token)) {
token.Cancelled();
}
}
CondVar& cv_;
std::optional<SuspensionToken> token_;
};
Awaiter Wait() { return Awaiter(*this); }
void NotifyOne() {
if (waiters_.empty()) return;
sched_.Schedule(waiters_.front());
waiters_.pop_front();
}
private:
Scheduler& sched_;
std::deque<SuspensionToken> waiters_;
};
// ---- User code: no token anywhere ----
class Channel {
public:
explicit Channel(Scheduler& sched) : cv_(sched) {}
void Push(int v) {
items_.push_back(v);
cv_.NotifyOne();
}
Co<int> Pop() {
while (items_.empty()) co_await cv_.Wait();
int v = items_.front();
items_.pop_front();
co_return v;
}
private:
std::deque<int> items_;
CondVar cv_;
};
Co<void> Consumer(Scheduler& sched, Channel& ch, int id) {
struct Cleanup {
int id;
~Cleanup() { std::cout << "consumer " << id << " cleanup (RAII)\n"; }
} cleanup{id};
for (;;) { // no exit path: cancellation destroys this frame instead
int item = co_await ch.Pop();
std::cout << "consumer " << id << " processes " << item << "\n";
co_await Yield(sched);
}
}
Co<void> Producer(Scheduler& sched, Channel& ch) {
for (int i = 0;; ++i) {
std::cout << "producer pushes " << i << "\n";
ch.Push(i);
co_await Yield(sched);
}
}
Co<void> StopAfter(Scheduler& sched, std::deque<CoThread*> threads, int ticks) {
for (int i = 0; i < ticks; ++i) co_await Yield(sched);
std::cout << "=== cancel requested ===\n";
for (CoThread* t : threads) t->Cancel(); // callbacks destroy the stacks
}
int main() {
Scheduler sched;
Channel ch(sched);
CoThread c1(ReportExit("consumer 1").handle);
CoThread c2(ReportExit("consumer 2").handle);
CoThread prod(ReportExit("producer").handle);
CoThread stopper(ReportExit("stopper").handle);
Spawn(sched, c1, Consumer(sched, ch, 1));
Spawn(sched, c2, Consumer(sched, ch, 2));
Spawn(sched, prod, Producer(sched, ch));
Spawn(sched, stopper, StopAfter(sched, {&c1, &c2, &prod}, 3));
sched.Run();
std::cout << "live coroutine frames after Run(): " << FrameCounter::live
<< "\n";
return FrameCounter::live == 0 ? 0 : 1;
}
Oct 2, 2026
[coroutine] c9 idiom of cancellation.
Dec 31, 2023
[Cppcon 2023] Expressing Implementation Sameness and Similarity - Polymorphism in Modern C++, Daisy Hollman
Reference:
https://youtu.be/Fhw43xofyfo?si=PcMFEsqb7NRiCmyX
Two different kinds of sameness
Interface sameness
- Enables users to treat things the same way in their code(create their own sameness)
- Cannot be removed later
- You can't change your user's code(at least not easily)
- Once you allow users to treat things as the same, it's very hard to change that later
- When done well: low code coupling(the degree of interdependence between software modules)
Implementation sameness
- Enables readers to understand and use existing sameness of similarity
- Can be changed or removed at any point in the future when it stops being helpful
- When done well: high code cohesion(the degree to which the elements inside a module belong together)
Reusing customization points.
Mixin mixins.
template<class> struct CRTPMixin;
template<template <class> class Mixin, class Derived>
struct CRTPMixin<Mixin<Derived>> {
consteval auto& self() { return static_cast<Derived&>(*this); }
consteval auto const& self() const { return static_cast<Derived const&>(*this); }
};
template<typename Derived>
struct PrintableElementwise : CRTPMixin<PrintableElementwise<Derived>> {
void print() const {
auto const& e = self().elements();
std::apply([](auto const&... el) {
([&]{ cout << el << "\n"; }(), ...);
}, e);
}
};As stated by Sy Brand's C++23’s Deducing this can help with the above
https://devblogs.microsoft.com/cppblog/cpp23-deducing-this/static_cast<Derived const&>(*this);
struct PrintableElementwise {
void print(this auto const& self) {
auto const& e = self.elements();
std::apply([](auto const&... el) {
([&]{ count << el << "\n"; }(), ...);
}, e);
}
};
struct Foo : PrintableElementwise {
int a;
double b;
std::string s;
auto elements() const {
return std::forward_as_tuple(x, y, z);
}
};
Above has mixed interface sameness with implementation sameness; which causes error:auto items = std::vector<PrintableElementwise>{/*...*/};
for (auto* i : items) {
i->print(); // error if derived type has no memfn elements().
}
Qualifier forwarding
template<class T>
void foo(T&& t) {
bar(std::forward<T>(t));
}
equivalent to:
template<class T>
void foo(T& t) {
bar(t);
}
template<class T>
using not_forwarding_ref = T;
template<class T>
void foo(not_forwarding_ref<T>&& t) {
bar(std::move(t));
}Don't Repeat Yourself(DRY)
'Every piece of knowledge must have a single, unambiguous, authoritative representation within a system'Separating the ownership mechanism (typical pattern for a class template customization point)
From:
template<class Thing>
class OwingCollection {
private:
vector<unique_ptr<Thing>> things_;
protected:
void for_each(/* concept */ std::invocable<Thing const&> auto&& f) const { /*...*/};
public:
void insert(unique_ptr<Thing>) {};
unique_ptr<Thing> remove(unique_ptr<Thing>) {};
bool contains(unique_ptr<Thing>) const {};
void remove_if(invocable<Thing const&> auto&&) {};
};
To:template<class Thing, template<class...> class Owner = unique_ptr>
class OwingCollection {
private:
vector<Owner<Thing>> things_;
protected:
void for_each(/* concept */ std::invocable<Thing const&> auto&& f) const { /*...*/};
public:
void insert(Owner <Thing>) {};
Owner <Thing> remove(Owner <Thing>) {};
bool contains(Owner <Thing>) const {};
void remove_if(invocable<Thing const&> auto&&) {};
};STD's example of separable pattern
C++20 Concepts
template<class T>
requires requires(T&& t) { { t.clear() } -> convertible_to<bool>; }
void do_the_stuff(T&& t) { /*...*/ }
Those two types fit for above API. struct Container {
// returns true if the container was
// non-empty before the clear
bool clear();
};
struct Color {
// returns true if opacity == 0
bool clear();
};
Concepts does not differentiate namespace.More places having the concept of 'sameness'
- 'Normal' functions (C like)
- Macros and Code generation
- 'Gross' but sometimes better than repeating things.
- Customization Point Objects(CPOs)
- Type erasure
- constexpr functions
- 'Sameness' of compile-time and runtime implementations.
- Dependency injection (needs reflection)
- Aspect-oriented programming(needs reflection)
- Decoration(needs reflection)
Dec 12, 2023
[C++] std::unstable_unique implement
std::unstable_unique implement by Andrei Alexandrescu
#include <cassert>
#include <vector>
template <class iterator, class BinaryPredicate>
iterator unstable_unique(iterator first, iterator last, BinaryPredicate p) {
if (first == last || std::next(first) == last)
return last; // 0 or 1-element range
++first; // position first on the first unknown element (first element will stay by definition)
bool first_is_known_duplicate = false; // see below for description
for (; first < last; ++first) {
if (!first_is_known_duplicate) {
if (!p(*first, *std::prev(first))) {
continue;
}
}
// Here we know that `*first` is a dupe and should be replaced. Also the range is not empty.
assert(first < last);
for (--last;; --last) {
if (first == last)
return first; // just past the last unique element
assert(first < last);
if (!p(*last, *std::prev(last)))
break;
}
assert(!p(*first, *last));
// Here we know we're good to replace *first with *last.
// Complicating matter: if we do so, we "forget" whether *std::next(first) is a duplicate of *first.
// Maintain `first_is_known_duplicate` to keep track of that.
first_is_known_duplicate = p(*first, *std::next(first));
*first = std::move(*last);
}
return first;
}
template <class iterator>
iterator unstable_unique(iterator first, iterator last) {
return unstable_unique(first, last, [](auto& a, auto& b) { return a == b; });
}
int main() {
std::vector<int> v1;
auto new_end1 = unstable_unique(v1.begin(), v1.end());
assert(v1.end() == new_end1);
std::vector<int> v2 = { 1, 2, 3, 4, 5 };
auto new_end2 = unstable_unique(v2.begin(), v2.end());
// std::cout << new_end2 - v2.begin() << '\n';
assert(v2.end() == new_end2);
// std::copy(v2.begin(), new_end2, std::ostream_iterator<int>(std::cout, " "));
assert(std::vector<int>({ 1, 2, 3, 4, 5 }) == v2);
std::vector<int> v3 = { 1, 1, 2, 3, 4, 5 };
auto new_end3 = unstable_unique(v3.begin(), v3.end());
assert((v3.begin() + 5 == new_end3));
assert(std::vector<int>({ 1, 5, 2, 3, 4, 5 }) == v3);
std::vector<int> v4 = { 1, 1, 2, 2, 3, 3, 4, 4, 5, 5 };
auto new_end4 = unstable_unique(v4.begin(), v4.end());
assert((v4.begin() + 5 == new_end4));
assert(std::vector<int>({ 1, 5, 2, 4, 3, 3, 4, 4, 5, 5 }) == v4);
std::vector<int> v5 = { 1, 1, 1, 1, 1 };
auto new_end5 = unstable_unique(v5.begin(), v5.end());
assert((v5.begin() + 1 == new_end5));
assert(std::vector<int>({ 1, 1, 1, 1, 1 }) == v5);
std::vector<int> v6 = { 1, 1, 1, 1, 1, 2 };
auto new_end6 = unstable_unique(v6.begin(), v6.end());
assert((v6.begin() + 2 == new_end6));
assert(std::vector<int>({ 1, 2, 1, 1, 1, 2 }) == v6);
std::vector<int> v7 = { 1, 2, 2, 3, 3, 3, 4, 4, 4, 4 };
auto new_end7 = unstable_unique(v7.begin(), v7.end(), [](int a, int b) { return a == b; });
assert((v7.begin() + 4 == new_end7));
assert(std::vector<int>({ 1, 2, 4, 3, 3, 3, 4, 4, 4, 4 }) == v7);
};
Dec 7, 2023
[C++] ValueOr(type) type check.
#include <type_traits>
#include <utility>
template <typename T>
struct Foo {
template <typename U>
T ValueOr(U&&) {
static_assert(sizeof(U) > 1);
return {};
}
};
template <typename T>
struct ForwardedDeclval {
T operator()();
};
template <typename... Ts, typename F>
consteval void InstantiateForStaticAssertions(F f) {
static_assert(std::is_same_v<decltype(f(ForwardedDeclval<Ts>()...)), void>);
}
template <typename T>
struct FooWrapper {
template <typename U>
T ValueOr(U&& u) {
InstantiateForStaticAssertions<Foo<T>, decltype(u)>(
[](auto t, auto u) { t().ValueOr(u()); });
return {};
}
};
int main() {
FooWrapper<int> f;
f.ValueOr(1);
//f.ValueOr('5');
}
May 10, 2023
[C++] SFINAE for testing type convertible
Reference:
https://en.cppreference.com/w/cpp/types/is_convertible
[C++][cppcon 2017] Write our own type trait
Use function parameter type to test if a incoming argument type is implicitly convertible to parameter type.
This trick can be used in SFINAE to test type convertibility.
#include <type_traits>
struct O2 {};
struct O1 {
O1() = default;
O1(const O2 &) {}
};
int main() {
// cannot be converted:
// decltype(void(std::declval<void (&)(O2)>()(std::declval<O1>()))) A;
decltype(void(std::declval<void (&)(O1)>()(std::declval<O2>()))) *A = nullptr;
};
Dec 10, 2022
[gcc] built-in functions; fast and optimized
Reference:
https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html
https://news.ycombinator.com/item?id=11760293
e.g.
__builtin_popcount
__builtin_popcountl
Oct 12, 2022
[C++23] std::unreachable / gcc::__builtin_unreachable
Jul 25, 2022
[C++] using private type as tag technique
#include <cctype>
#include <iostream>
#include <memory>
using namespace std;
class Fun {
private:
struct private_constructor {
// mark as explicit otherwise caller can abuse with init. private_constructor with '{}'
explicit private_constructor() = default;
};
public:
Fun(int data, private_constructor) {}
static Fun create_Fun(int data) { return Fun(data, private_constructor()); }
};
int main() {
//
//
Fun myFun = Fun::create_Fun(42);
}
Jul 18, 2022
[C++23] std::unreachable
Reference:
(msvc) __assume
(gcc/clang) __builtin_unreachable()
(c++23) std::unreachable
[[noreturn]] inline void unreachable()
{
// Uses compiler specific extensions if possible.
// Even if no extension is used, undefined behavior is still raised by
// an empty function body and the noreturn attribute.
#ifdef __GNUC__ // GCC, Clang, ICC
__builtin_unreachable();
#elifdef _MSC_VER // MSVC
__assume(false);
#endif
}
[C++][note] union tagging sample code
#include <new>
#include <string>
constexpr int TU_STRING = 0;
constexpr int TU_INT = 1;
constexpr int TU_FLOAT = 2;
struct TU {
union my_union {
struct i_type {
int type;
int i;
} i;
struct f_type {
int type;
float f;
} f;
struct s_type {
int type;
std::string s;
} s;
my_union(int i) : i{TU_INT, i} {}
my_union(float f) : f{TU_FLOAT, f} {}
my_union(std::string s) : s{TU_STRING, std::move(s)} {}
my_union(my_union const &other) {
// This is safe.
switch (other.i.type) {
case TU_INT:
::new (&i) auto(other.i);
break;
case TU_FLOAT:
::new (&f) auto(other.f);
break;
case TU_STRING:
::new (&s) auto(other.s);
break;
}
}
~my_union() {
// This is safe.
if (TU_STRING == s.type) {
s.~s_type();
}
}
} u;
TU(int i) : u(i) {}
TU(float f) : u(f) {}
TU(std::string s) : u(std::move(s)) {}
TU(TU const &) = default;
~TU() = default;
};
Jul 16, 2022
[C++] std::index_sequence example
Reference:
std::apply
std::index_sequence
<utility>
index_sequence is quite handy with argument deduction.
#include <utility>
#include <array>
template <typename... Args>
struct CustomType { };
template <typename... Args>
CustomType<Args...> method(const Args&... args) { return {}; }
template <typename T, std::size_t N, typename VariadicFunc, std::size_t... I>
auto methodApply(
const std::array<T, N>& arr, VariadicFunc func, std::index_sequence<I...>) {
return func(arr[I]...);
}
template <typename T,
std::size_t N,
typename VariadicFunc,
typename Indices = std::make_index_sequence<N>>
auto methodArr(const std::array<T, N>& arr, VariadicFunc func) {
return methodApply(arr, func, Indices());
}
template <typename T, std::size_t N>
auto method(const std::array<T, N>& arr) {
return methodArr(arr, [](const auto&... args) { return method(args...); });
}
int main() {
method(1.0f, 2.0f, 3.0f);
std::array<float, 4> arr{1.0f, 2.0f, 3.0f};
method(arr);
}
Jul 12, 2022
[vdso] extract vdso function from linux-vdso.so.1
We use vdso version of getcpu(...) for example; and its signature is
using Func = int (*)(unsigned* cpu, unsigned* node, void* unused);
Func resolveVdsoFunc() {
#if !defined(FOLLY_HAVE_LINUX_VDSO) || defined(FOLLY_SANITIZE_MEMORY)
return nullptr;
#else
void* h = dlopen("linux-vdso.so.1", RTLD_LAZY | RTLD_LOCAL | RTLD_NOLOAD);
if (h == nullptr) {
return nullptr;
}
auto func = Func(dlsym(h, "__vdso_getcpu"));
if (func == nullptr) {
// technically a null result could either be a failure or a successful
// lookup of a symbol with the null value, but the second can't actually
// happen for this symbol. No point holding the handle forever if
// we don't need the code
dlclose(h);
}
return func;
#endif
}
We could find this usage in Folly lib:
https://github.com/facebook/folly/blob/535d0313371b1c8d313ec8a1cd09b940fa992397/folly/concurrency/CacheLocality.cpp#L310
Jul 8, 2022
[C++] inline std::forward impl
// An inline std::forward replacement.
#define FMT_FORWARD(...) static_cast<decltype(__VA_ARGS__)&&>(__VA_ARGS__)
Jul 6, 2022
[C++] count bool 'true' snippet
template <bool B = false> constexpr auto count() -> size_t { return B ? 1 : 0; }
template <bool B1, bool B2, bool... Tail> constexpr auto count() -> size_t {
return (B1 ? 1 : 0) + count<B2, Tail...>();
}
[C++20] std::type_identity for Non-deduced contexts
Reference:
https://vsdmars.blogspot.com/2018/05/caccu2018-tricks-library-implementation.html
While reading {fmt} code:
https://github.com/fmtlib/fmt/blob/e6d478f8e88a357671c39bd39922ecac32aa2f58/include/fmt/core.h#L3107
template <typename... Args>
using format_string = basic_format_string<char, type_identity_t<Args>...>;
wondering why is type_identity_t needed?
// the identity template, often used to exclude specific arguments from deduction
// (available as std::type_identity as of C++20)
template<typename T>
struct identity { typedef T type; };
template<typename T>
void bad(std::vector<T> x, T value = 1);
template<typename T>
void good(std::vector<T> x, typename identity<T>::type value = 1);
std::vector<std::complex<double>> x;
bad(x, 1.2); // P1 = std::vector<T>, A1 = std::vector<std::complex<double>>
// P1/A1: deduced T = std::complex<double>
// P2 = T, A2 = double
// P2/A2: deduced T = double
// error: deduction fails, T is ambiguous
good(x, 1.2); // P1 = std::vector<T>, A1 = std::vector<std::complex<double>>
// P1/A1: deduced T = std::complex<double>
// P2 = identity<T>::type, A2 = double
// P2/A2: uses T deduced by P1/A1 because T is to the left of :: in P2
// OK: T = std::complex<double>
Jun 24, 2022
[C++] Stateful Metaprogramming in C++20
Reference:
https://mc-deltat.github.io/articles/stateful-metaprogramming-cpp20
Below code demonstrates even though the being generated at compile time the result can be different due to during the compile time state changes.
// declare of flag function, the function body doesn't exist
// unless template type setter being instantiated.
auto flag(int);
template<bool B> requires (!B)
struct setter {
// 'flag' definition
friend auto flag(int) {}
static constexpr bool b = B;
};
// declare [[nodiscard]] and consteval make sure the
// template function won't be elided by compiler.
template<bool FlagVal>
[[nodiscard]]
consteval auto nonconstant_constant_impl() {
if constexpr (FlagVal) {
return true;
}
else {
// 'setter' being instantiated.
setter<FlagVal> s;
return s.b;
}
}
template<
auto Arg = 0,
bool FlagVal = requires { flag(Arg); },
auto Val = nonconstant_constant_impl<FlagVal>()
>
constexpr auto nonconstant_constant = Val;
auto main() ->int{
// a = 0
// First evaluation in this TU; triggers 'setter' being
// instantiated.
// a = 0 (False)
constexpr bool a = nonconstant_constant<>;
// b = 1 (True)
constexpr bool b = nonconstant_constant<>;
// assertion passes.
static_assert(a != b);
}template<unsigned N>
struct reader {
friend auto counted_flag(reader<N>);
};
template<unsigned N>
struct setter {
friend auto counted_flag(reader<N>) {}
static constexpr unsigned n = N;
};
template<
auto Tag,
unsigned NextVal = 0
>
[[nodiscard]]
consteval auto counter_impl() {
constexpr bool counted_past_value = requires(reader<NextVal> r) {
counted_flag(r);
};
if constexpr (counted_past_value) {
return counter_impl<Tag, NextVal + 1>();
}
else {
setter<NextVal> s;
return s.n;
}
}
template<
auto Tag = []{}, // Each call generates different type.
auto Val = counter_impl<Tag>()
>
constexpr auto counter = Val;
int main() {
static_assert(counter<> == 0);
static_assert(counter<> == 1);
static_assert(counter<> == 2);
static_assert(counter<> == 3);
static_assert(counter<> == 4);
static_assert(counter<> == 5);
static_assert(counter<> == 6);
static_assert(counter<> == 7);
static_assert(counter<> == 8);
static_assert(counter<> == 9);
static_assert(counter<> == 10);
}#include <concepts>
#include <type_traits>
template<typename...>
struct type_list {};
template<class TypeList, typename T>
struct type_list_append;
template<typename... Ts, typename T>
struct type_list_append<type_list<Ts...>, T> {
using type = type_list<Ts..., T>;
};
template<unsigned N, typename List>
struct state_t {
static constexpr unsigned n = N;
using list = List;
};
namespace {
// used in reader; thus the 'state_func' shall be unique in each TU
// thus not violating the ODR
struct tu_tag {};
}
template<
unsigned N,
std::same_as<tu_tag> TUTag
>
struct reader {
friend auto state_func(reader<N, TUTag>);
};
template<
unsigned N,
typename List,
// Preventing accidentally passing random type thus violating ODR
// It must be anonymous type 'tu_tag'
std::same_as<tu_tag> TUTag
>
struct setter {
// generated 'state_func' will be unique in each TU thanks to 'TUTag'
friend auto state_func(reader<N, TUTag>) {
return List{};
}
static constexpr state_t<N, List> state{};
};
template struct setter<0, type_list<>, tu_tag>;
template<
// Preventing accidentally passing random type thus violating ODR
// It must be anonymous type 'tu_tag'
std::same_as<tu_tag> TUTag,
auto EvalTag,
unsigned N = 0
>
[[nodiscard]]
consteval auto get_state() {
constexpr bool counted_past_n = requires(reader<N, TUTag> r) {
state_func(r);
};
if constexpr (counted_past_n) {
return get_state<TUTag, EvalTag, N + 1>();
} else {
constexpr reader<N - 1, TUTag> r;
return state_t<N - 1, decltype(state_func(r))>{};
}
}
template<
// std::same_as is a concept; taking 2 arguments. <...> binds to back paramters while
// assigned type is bound to forefront paramter.
// Use to prevent accidentally passing random type thus violating ODR
// It must be anonymous type 'tu_tag'
std::same_as<tu_tag> TUTag = tu_tag,
auto EvalTag = []{},
auto State = get_state<TUTag, EvalTag>()
>
using get_list = typename std::remove_cvref_t<decltype(State)>::list;
template<
typename T,
// Preventing accidentally passing random type thus violating ODR
// It must be anonymous type 'tu_tag'
std::same_as<tu_tag> TUTag,
auto EvalTag
>
[[nodiscard]]
consteval auto append_impl() {
using cur_state = decltype(get_state<TUTag, EvalTag>());
using cur_list = typename cur_state::list;
using new_list = typename type_list_append<cur_list, T>::type;
setter<cur_state::n + 1, new_list, TUTag> s;
return s.state;
}
template<
typename T,
// Preventing accidentally passing random type thus violating ODR
// It must be anonmous type 'tu_tag'
std::same_as<tu_tag> TUTag = tu_tag,
auto EvalTag = []{},
auto State = append_impl<T, TUTag, EvalTag>()
>
constexpr auto append = [] { return State; };
int main() {
static_assert(std::same_as<get_list<>, type_list<>>);
append<int>();
static_assert(std::same_as<get_list<>, type_list<int>>);
append<float>();
static_assert(std::same_as<get_list<>, type_list<int, float>>);
append<char>();
static_assert(std::same_as<get_list<>, type_list<int, float, char>>);
}Jun 13, 2022
[C++][C++20] compile time heap allocate
For this reason, you can now use strings or vectors at compile time.
#include <vector>
#include <ranges>
#include <algorithm>
#include <numeric>
template<std::ranges::input_range T>
constexpr auto modifiedAvg(const T& rg) {
using elemType = std::ranges::range_value_t<T>;
// initialize compile-time vector with passed elements:
std::vector<elemType> v{std::ranges::begin(rg),
std::ranges::end(rg)};
// perform several modifications:
v.push_back(elemType{});
std::ranges::sort(v);
auto newEnd = std::unique(v.begin(), v.end());
// return average of modified vector:
auto sum = std::accumulate(v.begin(), newEnd, elemType{});
return sum / static_cast<double>(v.size());
}
// 注意,要用constexpr不然modifiedAvg為runtime.
constexpr auto avg = modifiedAvg(orig);
// use concept
// initialize compile-time vector with passed elements
template<std::ranges::input_range T>
consteval auto modifiedAvg(T rg) {
using elemType = std::ranges::range_value_t<T>;
std::vector<elemType> v{std::ranges::begin(rg), std::ranges::end(rg)};
}
However, note that we still cannot declare and initialize a vector at compile time that is usable at runtime:
int main() {
constexpr std::vector orig{0, 8, 15, 132, 4, 77}; // ERROR
}#include <vector>
constexpr auto returnVector() {
std::vector<int> v{0, 8, 15};
v.push_back(42);
return v;
}
constexpr auto returnVectorSize() {
constexpr auto coll = returnVector();
return coll.size();
}
int main() {
// constexpr auto coll = returnVector(); // ERROR
constexpr auto tmp = returnVectorSize();
}
#include <vector>
#include <ranges>
#include <algorithm>
#include <array>
template<std::ranges::input_range T>
consteval auto mergeValuesSz(T rg, auto... vals) {
// create compile-time vector:
std::vector<std::ranges::range_value_t<T>> v{
std::ranges::begin(rg), std::ranges::end(rg)};
(... , v.push_back(vals)); // and merge passed values
std::ranges::sort(v);
constexpr auto maxSz = rg.size() + sizeof...(vals);
std::array<std::ranges::range_value_t<T>, maxSz> arr{};
auto res = std::ranges::unique_copy(v, arr.begin());
return std::pair{arr, res.out - arr.begin()};
}constexpr Language Extensions
- You can now use heap memory at compile time.
- Runtime polymorphism is supported:
- You can now use virtual functions.
- You can now use dynamic_cast.
- You can now use typeid.
- You can have try-catch blocks now (but you are still not allowed to throw).
- You can now change the active member of a union.
- Note that you are still not allowed to use static in constexpr or consteval functions.
lamdba
template<typename... Args>
void foo(Args... args) {
// OK since C++20
auto l4 = [...args = std::move(args)] {
bar(args...); // OK
};
}
template<typename... Args>
void foo(Args... args) {
auto l4 = [&...fooArgs = args] {
bar(fooArgs...); // OK
};
}
new type:
char8_t
std::u8string
std::u8string_view
char8_t c = u8'@'; // character with UTF-8 encoding for character @
const char8_t* s = u8"K\u00F6ln"; // character sequence with UTF-8 encoding for Köln
Synchronized Output Streams:
https://en.cppreference.com/w/cpp/io/basic_osyncstream
#include <iostream>
#include <cmath>
#include <thread>
#include <syncstream>
void squareRoots(int num) {
for (int i = 0; i < num ; ++i) {
std::osyncstream coutSync{std::cout};
coutSync << "squareroot of " << i << " is "
<< std::sqrt(i) << '\n';
}
}
int main() {
std::jthread t1(squareRoots, 5);
std::jthread t2(squareRoots, 5);
std::jthread t3(squareRoots, 5);
}
For writing to file:
#include <fstream>
#include <cmath>
#include <thread>
#include <syncstream>
void squareRoots(std::ostream& strm, int num) {
std::osyncstream syncStrm{strm};
for (int i = 0; i < num ; ++i) {
syncStrm << "squareroot of " << i << " is "
<< std::sqrt(i) << '\n' << std::flush_emit;
}
}
int main() {
std::ofstream fs{"tmp.out"};
std::jthread t1(squareRoots, std::ref(fs), 5);
std::jthread t2(squareRoots, std::ref(fs), 5);
std::jthread t3(squareRoots, std::ref(fs), 5);
}
or:
#include <fstream>
#include <cmath>
#include <thread>
#include <syncstream>
void squareRoots(std::ostream& strm, int num) {
for (int i = 0; i < num ; ++i) {
strm << "squareroot of " << i << " is "
<< std::sqrt(i) << '\n' << std::flush_emit;
}
}
int main() {
std::ofstream fs{"tmp.out"};
std::osyncstream syncStrm1{fs};
std::jthread t1(squareRoots, std::ref(syncStrm1), 5);
std::osyncstream syncStrm2{fs};
std::jthread t2(squareRoots, std::ref(syncStrm2), 5);
std::osyncstream syncStrm3{fs};
std::jthread t3(squareRoots, std::ref(syncStrm3), 5);
}
Jun 11, 2022
[algorithm] fast string hash function
auto hashed = [] (const char* str) consteval {
std::size_t hash = 5381;
while (*str != '\0') {
hash = hash * 33 ^ *str++;
}
return hash;
};
// requires hashed() in compile-time context
enum class drinkHashes : long {
beer = hashed("beer"),
wine = hashed("wine"),
water = hashed("water"),
};
std::array arr{hashed("beer"), hashed("wine"), hashed("water")};
Oct 12, 2017
[C++] allocator template code
https://howardhinnant.github.io/allocator_boilerplate.html
http://en.cppreference.com/w/cpp/container/vector/operator%3D
http://en.cppreference.com/w/cpp/memory/allocator_traits
C++11 and forward:
The commented out code represents functionality that std::allocator_traits<allocator<T>> defaults for us.
Notes:
- is_always_equal is new for C++11 (
hopefully that will be C++17). It is now in C++17. - The default implementation for max_size() is not incredibly useful.
Better if:
return std::numeric_limits<size_type>::max() / sizeof(value_type); - Under discussion is the possibility to remove the requirement that you provide operator== and operator!= if is_always_equal{} is true.
- The nested types reference and const_reference are no longer required in C++11 (as they were in C++03).
- The member functions address(reference) and address(const_reference) are no longer required in C++11 (as they were in C++03).
- Allocator must be CopyConstructible and MoveConstructible. If propagate_on_container_copy_assignment{} is true,
- allocator must be CopyAssignable if propagate_on_container_move_assignment{} is true, allocator must be MoveAssignable.
- If propagate_on_container_swap{} is true, allocator must be Swappable.
- If they exist, these operations should not propagate an exception out.
- However they do not need to be marked with noexcept.
Recommend marking them with noexcept if the compiler does not implicitly do so,
so that traits such as is_nothrow_copy_constructible<allocator<T>> give the right answer. - If two allocators compare equal, that means that they can deallocate each other's allocated pointers.
- If two instances of your allocators can't do this, they must not compare equal to each other, else run time errors will result.
- However copies, even converting copies, are required to compare equal.
template <class T>
class allocator
{
public:
using value_type = T;
// using pointer = value_type*;
// using const_pointer = typename std::pointer_traits<pointer>::template
// rebind<value_type const>;
// using void_pointer = typename std::pointer_traits<pointer>::template
// rebind<void>;
// using const_void_pointer = typename std::pointer_traits<pointer>::template
// rebind<const void>;
// using difference_type = typename std::pointer_traits<pointer>::difference_type;
// using size_type = std::make_unsigned_t<difference_type>;
// template <class U> struct rebind {typedef allocator<U> other;};
allocator() noexcept {} // not required, unless used
template <class U> allocator(allocator<U> const&) noexcept {}
value_type* // Use pointer if pointer is not a value_type*
allocate(std::size_t n)
{
return static_cast<value_type*>(::operator new (n*sizeof(value_type)));
}
void
deallocate(value_type* p, std::size_t) noexcept // Use pointer if pointer is not a value_type*
{
::operator delete(p);
}
// value_type*
// allocate(std::size_t n, const_void_pointer)
// {
// return allocate(n);
// }
// template <class U, class ...Args>
// void
// construct(U* p, Args&& ...args)
// {
// ::new(p) U(std::forward<Args>(args)...);
// }
// template <class U>
// void
// destroy(U* p) noexcept
// {
// p->~U();
// }
// std::size_t
// max_size() const noexcept
// {
// return std::numeric_limits<size_type>::max();
// }
// allocator
// select_on_container_copy_construction() const
// {
// return *this;
// }
// using propagate_on_container_copy_assignment = std::false_type;
// using propagate_on_container_move_assignment = std::false_type;
// using propagate_on_container_swap = std::false_type;
// using is_always_equal = std::is_empty<allocator>;
};
template <class T, class U>
bool
operator==(allocator<T> const&, allocator<U> const&) noexcept
{
return true;
}
template <class T, class U>
bool
operator!=(allocator<T> const& x, allocator<U> const& y) noexcept
{
return !(x == y);
}
Jun 11, 2015
[c++] extract inner type
#include
using namespace std;
class Fun
{
struct InnerType
{
int i{42};
};
public:
auto run()
{
return InnerType{};
}
auto run2() -> InnerType;
};
template< typename R, typename _>
void extractInnerType( R(_::*)() )
{
cout << R{}.i << endl;
}
template< typename T>
T innerType{};
int main(void)
{
// Blog's question:
Fun f;
decltype(f.run()) d{};
cout << d.i << endl;
//variable template
cout << innerType<decltype(f.run())>.i << endl;
//--- c++98 style
extractInnerType(true ? nullptr : &Fun::run2);
}