这些实现非常简单,甚至不能说实现,只是“包装”,“套壳”,但是总而言之能不自己写就不要自己写。
- namespace mylib {
-
- template<typename...Ts, typename Type = std::common_type_t
> - constexpr auto min(const Ts&... args)noexcept {
- return std::min({ static_cast
(args)... }, std::less<>()); - }
-
- template<typename...Ts, typename Type = std::common_type_t
> - constexpr auto max(const Ts&... args)noexcept {
- return std::max({ static_cast
(args)... }, std::less<>()); - }
-
- template<typename...Ts, typename Type = std::common_type_t
> - constexpr auto sum(const Ts&...args)noexcept {
- return (static_cast
(args) + ...); - }
-
- template<class ...Args,class F>requires std::is_pointer_v
- inline auto bind(F f, Args&&...args) {
- return [=]()mutable
- {
- return f(std::forward
(args)...); - };
- }
-
- template<class ...Args, class F>requires std::is_class_v
- inline auto bind(F f, Args&&...args) {
- return [=]()mutable
- {
- return f(std::forward
(args)...); - };
- }
-
- }
首先你需要学习过模板,再学习过形参包,constexpr,lambda,可变参数,折叠表达式,完美转发,右值引用,约束与概念,然后就可以了,非常的简单
记得打开编译器的c++20选项
单元测试如下:
- int f(int a) {
- fmt::print("{} \n", a);
- return a;
- }
-
- int main() {
- fmt::print("{} \n", my::max(1, 2, 3, 4));
- fmt::print("{} \n", my::min(1, 2, 3, 4));
-
- fmt::print("{} \n", my::min(10.2, 2.9, 3.9, 4));
- constexpr auto N = my::min(10.2, 2, 3.9, 4);
-
- fmt::print("{} \n", my::max(10.2, 2.9, 3.9, 4));
- constexpr auto N2 = my::max(10.2, 2, 3.9, 4);
-
- fmt::print("{} \n", my::sum(1.1, 2));
-
- std::function F = f;
- auto p = my::bind(F, 1);
- p();
-
- auto p2 = my::bind(f, 10);
- p2();
-
- auto p3 = my::bind([](int v) {return f(v); }, 10);
- p3();
- }
在visual studio2022下编译通过,还使用了三方库fmt,链接如下: