可变模板参数包迭代

序 如果你写了一个模板函数,模板函数里使用了 可变参数。比如你写了个 template<typename... Args> int print(Args... args); 那么,要如何去访问这些可变的参数呢? 方法 1 使用递归法。比如定义2个 print, 一个是单参数的,另一个是 2个模板参数的。 template<typename Arg> int print(Arg arg); template<typename Arg1, typename... Args> int print(Arg1 arg1, Args... args) { print(arg1); print(args...); } 在可变参的 print 里, 它首先将第一个参数调用了单参数版的 print. 接着把剩下的参数调用自身。 如果剩下的参数就一个了,那么编译器也是匹配到单参数版的 print 从而结束递归。 方法 2 使用 折叠表达式 template<typename... Args> int print(Args... args) { (print_one(args), ...); } 在这个方法里,(print_one(args), ...);就是所谓的 折叠表达式。 它的意思就是把 前面的 重复一下。每次重复的时候,各使用参数包里的一个参数。 方法 3 打包进 std::tuple 后使用。比如 template<typename... Args> int print_tuple(std::tuple<Args...> tuple_arg) { // ??? } template<typename... Args> int print(Args... args) { print_tuple(std::forward_as_tuple(args...)); } 吼吼,那么问题来了, tuple 版本要怎么实现? ...

November 13, 2024

从模板的模板论程序员的美学

在编写 µcoro 的时候,曾经对一个模板类的成员函数犯难了。那就是等待器三件套之一的 await_suspend 函数。 我为template<typename T> class awaitable 的三件套使用这样一个模板签名 template<typename PromiseType> auto await_suspend(std::coroutine_handle<PromiseType> h); 其中,这个 PromiseType 必须得是 awaitable<T>::promise_type (也就是 awaitable_promise<T> ) 的其中一个实例。 按前C++ 时代的做法,这个成员函数应该这么写 template<typename Any> auto await_suspend(std::coroutine_handle<awaitable_promise<Any>> h); 这种写法,可以保证接收到的 h 参数,其 Promise 类型必然是 awaitable_promise 的一个参数化实例。 但是,与此同时,我还希望要为 std::coroutine_handle 这样的通用参数写一个单独的处理代码。 于是,使用按前C++ 时代的做法,我需要写2个 await_suspend, 他们分别是 template<typename Any> auto await_suspend(std::coroutine_handle<awaitable_promise<Any>> h); auto await_suspend(std::coroutine_handle<> h); 对这两个类型的 promise handle, 各自有一套不同的处理代码。 但是,老王提出了不同意见。他认为,std::coroutine_handle 在标准库里,就一种表示方式,那就是 template<typename PromiseType> class std::coroutine_handle; 他批评我说,std::coroutine_handle<awaitable_promise<Any>> 这样的写法不直观。而且还写了两个 await_suspend 到底哪个在干活,得多费脑细胞。 后来,函数签名恢复成了 template<typename PromiseType> auto await_suspend(std::coroutine_handle<PromiseType> h); 但是,使用了 enable_if 之类的模板技巧,外加在 awaitable_promise 里添加一些辅助佐料,实现了 ...

October 19, 2024