Design and implement an "Accumulator" class (complete)

Mongoose: aggregate() 方法实现聚合函数 原载于 https://szhshp.org/tech/2019/09/07/mongodbaggregatefunc.html, 转载请注明 需求描述 首先我有一个 Item 的 collection: type Item { _id: String itemname: String! itemid: String! itemtype: String! par... 阅读详情
  
Abstract
 
A few months ago, I wrote two snippets that composed the basics of the initial half of this article. This one is the complete and formal version.
 
Often than not, a seemingly trivial problem could become a challenge when you take various requirements into account, when you have to decide among a number of design options, and when you have to balance a variety of tradeoffs. Challenges like this are what a library programmer faces every day. This article will show how I think, design, and implement for the task of adding things up, i.e., an accumulator. The task may sound too trivial to deserve an article, but it will actually not if you put all requirements together to create a really flexible and customizable framework. You will see that modern C++ template techniques play as the key weapon for taking down many difficult design problems.
 
Copyright (c) prototype, all rights reserved。
在不对原文内容(包括作者信息)做任何改动的前提下,欢迎自由转载。
 
1. The primer
 
Often I come across writing a small fragment of code that sums up things. The code usually has the following look:
 
float sum;   // I could forget to properly initialize `sum'.
int n = 0;
while (...) {
  sum += array[i];
   n++;
   ... // some other stuff
}
 
Potential problems for codes like this are the following:
                    I.      The programmer has to remember to properly initialize the sum variable.
                 II.      The programmer has to keep a counter around and initialize it before the summation starts and increment it along with each addition operation.
               III.      If the type of the sum variable changes, the summation code may likely change.
              IV.      For floating number summations, a simple summation like the above code may not be accurate enough, whereas more accurate summation is actually quite complicated. The same thing could also happen for other types. For complicated algorithms, it is essential to hide the implementation detail so as to keep the client code as clean and easy to understand and maintain as possible.

Below we will attack these problems one by one. The actions will eventually lead to a complete and customizable framework that allows user to treat any summation in a consistent and clean way.
 
2. The class and the interface
 
For problems I and II, the correct approach is generally to create a class. This is a very natural decision so I would like to skip its rationalization for succinctness. The crucial part is the interface of the class. Let’s think about it carefully:
1.      Problems I and II require that the sum variable and the counter are initialized in an automatic fashion. Thus we need to define a default ctor for doing this.
2.      The default initialization might not always be what a user wants, a ctor for customized initialization should also be provided. The most natural way to initialize a variable is to set a value to it. We therefore need to define another ctor for the class. This ctor will take only 1 parameter that is a constant reference to the initializing value.
3.      A member function should be available for accumulating a given value to the sum. Plain member function can work, but += operator is a more natural interface.
4.      The summation result should be available for the user. Exposing a data member violates the encapsulation and should always be avoided. A member function should be provided. Let’s call it “sum()”.

The above is the basic interface. However, a couple of useful things can also be added.

5.      The interface allows the user to know how many values have been accumulated. So a member function can be provided for reading the current value of the counter. Let’s call this function “size()”, indicating the size of the data sample.
6.      It is almost certain that an average will be calculated after summation. So a member function for this can be useful. Let’s call this function “average()”.
 
OK, admitted that the actual process of defining the interface may not sound as straightforward as I wrote here, but let’s be succinct and get to the most exciting part faster. Once the interface is defined, an initial implementation of the class is easy:
 
class Accumulator
{
 public:
   Accumulator() : sum_( 0 ), size_( 0 ) { }
   explicit Accumulator( const float& a ) : sum_( a ), size_( 0 ) { }
   Accumulator& operator += ( const float& a ) { sum_ += a; return *this; }
   unsigned long size() const { return size_; }
   float sum() const { return sum_; }
   float average() const { return sum() / size(); }
 private:
   float sum_;
   unsigned long size_;
};
 
Just an aside to clarify a potential snag: “explicit” is a C++ keyword, by putting it before a ctor, we prevent unwant implicit type conversion from happening. Specifically speaking for this case, a declaration like `explicit Accumulator( const float& a )’ will make a code like the following produce a compile error:
 
void foo( const Accumulator& a );
float a;
…
foo( a );     // error
 
If the ctor was defined without “explicit”, the compiler would generate a temporary “Accumulator” object (by calling to the ctor) and then pass this object into “foo” without any complaints. Such a behavior is a source of bugs and should be avoided unless it is what you really want to implement.
 
It is worth mentioning a technical merit in the implementation of `average()’. It uses `sum()’ and `size()’, instead of `sum_’ and `size_’, to obtain the average. It is always better to use public member functions instead of member data in your implementation no matter it is within or outside the same class. This is simply because public member functions are much more stable than member data. As the class evolves to become more complicated and powerful, an implementation using `sum_’ and `size_’ will not be possible any more.
 
Now, with this implementation, we basically solved problems I and II. Next, we need to genericitize this implementation for many different types.
 
3. The generic implementation
 
To obtain a generic version of the implementation, we can replace the `float’ with a generic type `T’ to get the initial templatized version. Then we examine and fix any problems resulted by the templatization. This is useful approach to obtaining generic design and implementations.
 
The initial template version looks like this:
 
template <typename T>
class Accumulator
{
 public:
   Accumulator() : sum_( 0 ), size_( 0 ) { }
   explicit Accumulator( const T& a ) : sum_( a ), size_( 0 ) { }
   Accumulator& operator += ( const T& a ) { sum_ += a; return *this; }
   unsigned long size() const { return size_; }
   T sum() const { return sum_; }
   T average() const { return sum() / size(); }
 private:
   T sum_;
   unsigned long size_;
};
 
This is actually a pretty good template that works for all built-in types that have well-defined += operators. However, there are still problems:
  1. For a user define type (UDT), `sum_’ may be unable to be initialized by zero.
  2. A UDT may not define += operator.
  3. The user may not want the returned value of `average()’ to be of the same type as the data. For example, the user may want to sum up integer data whereas obtaining an average of `float’ type.
Below let’s try to solve these problems.
 
For poblem (1), we first need to realize that there is no way to know a priori how an object of any type should be initialized. The best bet is that if the user wants an `Accumulator’ object to be constructed via the default ctor he also wants the `sum_’ to be initialized by the default ctor of `T’. This assumption is the best that we can do at this point (but we will indeed do better later on, I promise). For now, we accept this assumption and make it a requirement or constraint for `T’. This means that default ctor should be changed to this:
 
Accumulator() : sum_(), size_( 0 ) { }
 
You might doubt whether this works for build-in types. The answer is yes. The form of expression like `sum_()’ means the object (`sum_’ in this case) is zero initialized and has no difference from `sum_( 0 )’.
 
Problem (2) is difficult for now. As we will see below, the solution will change the framework of the class significantly. Let’s skip this for now, and we just make it a requirement for `T’ that the UDT must have a well-defined += operator.
 
Problem (3) is not a severe problem. The user can always use `sum()’ and `size()’ and necessary type conversions to get the wanted average value. But since we already put `average’ into the interface, we should complete the work. We need the user to specify what type of value he needs `average()’ to return. To this end, a simple and yet elegant way to overload the `average()’ function with a function template like this:
 
template <typename S> S average() const { return S( sum() ) / size(); }
 
The client code will look like this:
 
Accumulator<int> a;
…
float b = a.average<float>();
 
This beautifully solves our problem (3).
 
OK. Putting these solutions together (omitted here), we get a generic implementation of the `Accumulation’ class. It works nicely for any type that satisfies the two constraints mentioned above.
 
3. The customizable framework
Now, let’s think about the problems of our generic implementation of `Accumulator’:
 
  1. `T’ must satisfy the aforementioned constraints in order to use the template. This considerably restricts the use of the template.
  2. `sum_’ has to be the same type as the data, which is not always wanted. For example, we sometimes want to use `double’ for `sum_’, while the data are still `float’. There could be more complicated scenarios, for example, `sum_’ may not even be stored as a single variable.
 
The problems are unfortunately fundamental for our implementation; by no means, we can solve them within the current framework of `Accumulator’. What these problems really require for the implementation is that the user is allowed to define, for `Accumulator’, how `sum_’ is stored, how summation is performed, how average is obtained, and so on. In other words, they require a mechanism to plug-in not only a type (our generic implementation already did this), but also algorithms and internal data structures. Can we do this?
 
The short answer is yes. Long answer is what follows. Below, I will just show the implementation and then explain how it works.
 
namespace private
{
 template <typename T>
 class Simple
 {
 public:
    typedef T DataType;
 
    Simple() : sum_(), size_( 0 ) { }
    Simple( const T& t ) : sum_( t ), size_( 0 ) { }
    void operator += ( const T& rhs ) { sum_ += rhs; size_++; }
   const T& sum() const { return sum_; }
    T average() const { return sum_ / size_; }
    unsigned long size() const  { return size_; }
    template <typename S>
   S average() const { return S( sum_ ) / size_; }
 
 private:
   T              sum_;
   unsigned long size_;
 };
}
 
template <typename T, typename M = private::Simple<T> >
class Accumulator : private M
{
 public:
   Accumulator() : M() { }
   Accumulator( const T& t ) : M( t ) { }
 
   Accumulator& operator += ( const T& rhs ) { M::operator += ( rhs ); return *this; }
 
  T             sum    () const { return T( M::sum() ); }
   T             average() const { return T( M::average() ); }
   unsigned long size   () const { return M::size(); }
 
   template <typename S>
   S average() const { return M::template average<S>(); }
};
 
In this implementation, we use a powerful technique that I called it template mixin. What this technique does is to derive the current class from a template argument so that the current class’ behavior is completely or partly customized by the base class. In some sense, this technique can be thought opposite to the object-oriented method. In this technique, you define the most derived class first, leaving the base class later for the user to define. In the object-oriented method, you define the base class first and let the user define the derived class. In this technique, the interface is defined at the most-derived class, whereas in the object-oriented method, the interface is defined at the base class. This opposite thinking actually results in a very important feature – static polymorphism, and no virtual functions. In our case, the base class `M’ is where all the algorithms and data structure are implemented for the type `T’. This leaves the `Accumulator’ a real framework that basically only defines the interface, leaving all behavior to be customized by the UDT `M’. Because it doesn’t really define the implementation in any specific way by itself, `Accumulator’ achieves the maximal customizability.
 
OK. That is the general idea. Let’s inspect `Accumulator’ closely to clarify a few important points in the design and implementation:
 
1.      The implementation of the member functions of `Accumulator’ is just very thin wrapping of the corresponding member function of `M’. Any compiler should be able to remove the overhead of the additional layer of function call, so no loss of efficiency.
2.      By defining `private::Simple<T>’, we provide implementation for any types that satisfies the aforementioned constraints. We made this implementation the default by the template expression `typename M = private::Simple<T>’.
3.      The user can change the default behavior by plugin their own class for `M’. Let’s see this through an example:

To use `double’ type, instead of `float’ type to sum over a number data of `float’ type, we just change the declaration from:
Accumulator<float> a;
to
Accumulator<float, private::Simple<double> > a;
All other code remains the same.

4. Conclusions
 
Through three versions of the `Accumulator’ class, we incrementally solved the problems I~IV, eventually achieving a flexible and fully customizable implementation. This is a general approach how I personally design and implement software.
 
C++ template is an essential and very powerful tool for conquering the difficult design and implementation problems. Whereas generics is a powerful technique that liberates the programmer from implementation for each specific case, it can still cause rigidity on the underlying data structure and algorithms. The mix-in technique, as I demonstrated here, is a key to breaking such rigidity for maximal freedom.
Copilot在游戏开发中的应用:Unity脚本自动生成实践 2021年GitHub Copilot的发布,为代码自动生成带来了革命性突破。作为基于GPT模型训练的AI辅助编程工具,Copilot能根据注释、函数名、代码上下文,实时生成符合语法和逻辑的代码片段,甚至完整脚本。减少重复劳动:自动生成模板代码(如生命周期、结构),让你专注核心逻辑;降低API学习成本:对Unity特有的组件(RigidbodyAnimator)、类(),Copilot能生成符合最佳实践的调用代码;统一代码风格:通过团队共享提示词模板,让生成的代码符合项目规范;快速原型迭代。 阅读详情

相关推荐

极路由 极1s J1S hc5661 刷padavan固件

极路由1S刷机指南 准备工作: 下载Breed不死固件 通过WinSCP上传或直接wget获取 执行mtd命令写入Breed 关键步骤: 进入Breed控制台(按住Reset键开机) 备份原厂固件和密钥 下载Padavan固件(RT-N14U-GPIO-12-xiaodu-ji1S-128M.trx) 刷机过程: 在Breed控制台更新固件 等待自动重启完成 初始设置: 管理地址:192.168.123.1 默认账号:admin/admin 无线名称:PCDN 无线密码:1234567890 注意事项:切勿

SimonLiu的博客 1336

MongoDB 使用说明

pymongo查询范围内的值并计数 match_dict = {"$match": {"$and": [{"area": {"$gte": number_list[j]}}, {"area": {"$lte": number_list[j + 1]}}]}} group_dict = {"$group": {"_id": None, "占比": {"$sum": "$weight"},

GMH的博客 1420

解决VMWare ESXi PCIe直通显卡导致的DevicePowerOn启动故障

本文详细解析了VMWare ESXi中PCIe直通显卡导致的DevicePowerOn启动故障,重点分析了MMIO空间不足的根本原因,并提供了完整的解决方案。通过修改.vmx文件中的关键参数,如pciPassthru.64bitMMIOSizeGB,可以有效解决显存分配问题。文章还涵盖了硬件兼容性检查、性能调优技巧及大规模部署的实战案例,帮助用户彻底解决显卡直通难题。

weixin_42537919的博客 592

A string ref, “title“, has been found within a strict mode tree. String refs are a source of po

react严格模式报错:Warning: A string ref, "title", has been found within a strict mode tree. String refs are a source of potential bugs and should be avoided. We recommend using useRef() or createRef() instead. Learn more about using refs safely here:

不确定因素的博客 1366

SolidWorks Routing标准件库搭建与实用技巧分享

在机械设计中,管路、管筒与电气线束的布线是影响装配效率的关键环节。SolidWorks Routing 作为专业的三维布线模块,依赖标准件库中的连接点(CPoint)与配合参考来实现接头的自动吸附和路径生成。然而系统自带库存在型号不全、配置分散、版本兼容性差等问题,导致设计师大量时间耗费在翻型号和手动配合上。通过自建标准件库,并配合 Routing Library Manager 统一登记路径与配置,可显著提升管道布线、管筒走向及电气线束布置的效率。本文从连接点原理、配置命名、模板属性等底层逻辑出发,梳理了

weixin_42510201的博客 318

从零构建安全通信:mbedtls与ECDSA在嵌入式系统中的实战指南

本文详细介绍了如何在嵌入式系统中使用mbedtls和ECDSA实现安全通信,重点探讨了ECDSA相比RSA的优势、mbedtls的模块化裁剪策略、密钥安全存储方案以及完整的签名验签流程。通过实战案例和优化技巧,帮助开发者在资源受限环境下构建高效可靠的安全通信系统。

weixin_28338005的博客 692

ubuntu安装mongod、配置用户访问、添删改查

2.2、验证是否启动成功。1.1包管理公钥导入。1.3更新软件包列表。

heming20122012的专栏 841

OpenCv案例(七): 基于OpenCvSharp计算图像的清晰度(自动对焦)

自动对焦,其实是对相机成像的清晰值得计算,若对焦不清晰,成像的清晰度低,视觉效果模糊。若是在工业检测行业,对焦不准确,可能会造成严重后果;对焦准确的图像,其清晰度高,对比度鲜明,层次明显。

qq_37835727的博客 7127

A string ref,“slider“,has been found within a strict mode tree.String refs are a source of potential

问题描述 A string ref,“slider”,has been found within a strict mode tree.String refs are a source of potential bugs 解决方法

l1090865的博客 2853

以太网GMAC-RK3568

第 2 章和第 3 章中针对 RMII/RGMII 接口芯片和 USB 以太网两种类型芯片在 SDK 上的配置做详细的描述,第 4 章介绍以太网在 Android 上的相关调用接口。第 5 章提供常见问题的排查建议由于在 RK 系列的 SoC 中内置了以太网 MAC 控制器,所以只需要搭配一颗以太网 PHY 芯片,即可实现以太网卡功能按照规范,即使是不同厂家的 PHY,仍然有一部分寄存器的定义是通用的,只要配置了这些通用的寄存器,基本上 PHY 就可以正常工作代码位置在。

qq_24093081的博客 1949

SAP ERP 系统订单行项目中的计划行(Scheduled Line)详解

*计划行(Scheduled Line)**是SAP系统中订单行项目(如采购订单、生产订单、销售订单等)的细分单元,用于记录和管理物料的供应或需求计划。每个订单行项目可以包含一个或多个计划行,每个计划行对应具体的交货日期、数量、需求类型(如采购申请、生产订单、库存调拨等)以及相关的物流控制参数。简单来说,计划行是系统对某一物料在特定时间点的供需状态的详细规划,它将订单分解为更细粒度的执行步骤,确保供应链各环节(如采购、生产、仓储)能够按计划协同工作。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 3411

CANN仿真器AIC性能问题指南

AIC-side pipeline bound diagnosis and fix solutions. All metric paths refer to fields in `summary.json`. > **Reading order**: scan the Quick Reference Table for a row matching your symptoms, then jum

gitblog_00464的博客 821

Linux 下安装 openjdk 17【详细步骤】

JDK17,安装教程。

甘蓝的专栏 7549

React学习笔记-----ref

ref在react初期的时候是用于方便操纵dom元素的,就类似于document.getElementById()这种形式,获取dom树中的某个dom节点. 到现在为止,主要有三种使用形式 方式1: string类型绑定 类似于vue中的ref绑定方式,可以通过this.refs.绑定的ref的名字获取到节点dom 注意的是 这种方式已经不被最新版的react推荐使用,有可能会在未来版本中遗弃 方式2: react.CreateRef() 通过在class中使用React.create.

iblackboy的博客 500

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

React中使用antd-mobile组件库中的跑马灯组件报错严格模式问题

通过ceact-react-app搭建的React项目,在使用antd-mobile组件库中的Carousel(跑马灯)组件时,报如下错误: Warning: A string ref, “slider”, has been found within a strict mode tree. String refs are a source of potential bugs and should be avoided. We recommend using useRef() or createRef()

筱竹的博客 2453

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

index.js:1 Warning: A string ref, “slider“, has been found within a strict mode tree. String refs ar

控制台报错 index.js:1 Warning: A string ref, "slider", has been found within a strict mode tree. String refs are a source of potential bugs and should be avoided. We recommend using useRef() or createRef() instead. Learn more about using refs safely here: http.

imkaifan的博客 945

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

React项目中使用antd-mobile组件中的Carousel 走马灯报错严格模式问题

通过ceact-react-app搭建的React项目,在使用antd-mobile组件库中的Carousel(跑马灯)组件时,报如下错误(但是不影响跑马灯的使用): Warning: A string ref, "slider", has been found within a strict mode tree. String refs are a source of potential bugs and should be avoided. We recommend using useRef() or

莹儿的博客 2811

React 属性, 函数式组件以及Hook

属性以及函数式组件,HookReact的五个属性PureComponentrefchildrendangerouslySetInnerHTMLkey的问题函数式组件React hooks什么是HookReact Hooks的优势常用HookHook的使用规则总结: 五个属性: PureComponent、ref、children、dangerouslySetInnerHTML、key React的五个属性 PureComponent 个人理解是PureComponent 是类组件的情况下,它是用来继承的

ZZZ___jh的博客 877

Property description must be an object

本篇文章参考以下博文 Uncaught TypeError: Property description must be an object Object.defineProperties() 文章目录报错区别Object.definePropertyObject.defineProperties 报错   最近在使用 Object.defineProperties 定义属性时报错: Property description must be an object   报错说明:属性描述必须是

不见浅诗的博客 9086

The field 'key' must be an object, but got undefined

环境 mongodb:3.4 工具:robo 3T 1.1 前言 再给一张表创建局部索引时,报错了: /* 1 */ { "raw" : { "shard4/10.19.139.216:27048,10.19.30.210:27048" : { "ok" : 0.0, "errmsg" : "The field

山鬼谣的专栏 3651

LeetCode 简单算法题

使用Nodejs 抓取的LeetCode 简单算法题  一步一步来,先攻破所有简单的题目,有些题目不适合使用JS解决,请自行斟酌Letcode 简单题汇总104. Maximum Depth of Binary Tree||        Given a binary tree, find its maximum depth.The maximum depth is the number of n...

知无涯 8584

项目中报错:Warning: count():Parameter must be an array or an object that implements Countable的解决方案

报错信息:Warning: count(): Parameter must be an array or an object that implements Countable 这主要是7.2版本更新,部分方法变得更加严谨了 当传递一个无效参数的时候,count()函数会抛出warning的警告 解决办法 1.如果是使用laravel框架报错的话,composer update一下就可以修...

不和贪婪的人相对 不为薄情寡义的人流泪 这世界嘲笑我的人很多 你只是其中一个 不为岁月流逝蹉跎 不随潮流的是否去附和 2万+

Leetcode 解题报告

据说刷完leetcode是准备编程面试的第一步。想到明年可能就要开始找工作了,先准备着吧。 计划今年11月份前做完,大概平均每天2-3题,难度应该不大,贵在坚持! 代码放在github上,地址:https://github.com/xingjian-f/Leetcode-solution 简略解题报告 1 Two Sum 三种解法: 1 暴力枚举所有的两两组合,检查它们的和是否等于

勿忘初衷 1万+

在高性能计算中慎用C++ std::complex

 Copyright (c) prototype, all rights reserved。 在不对原文内容(包括作者信息)做任何改动的前提下,欢迎自由转载。 两年多前写的内部资料。现在自己把它翻成中文,贴到我的blog上来。 近来闲暇时,我用C++和表达式模板(expression template)技术实现了一个复数类(注意:是类,而不是类模板)— Complex。

prototype的专栏 1万+

废弃的C++语言特性 - Deprecated C++ features explained

Copyright (c) prototype, all rights reserved。 在不对原文内容(包括作者信息)做任何改动的前提下,欢迎自由转载。0.      必要说明:所谓“废弃”(deprecated, or obsolescent) 的语言特性是指那些在目前的C++标准(ISO/IEC 14882:1998,以下简写为C++98)下仍然是合法的,但在新版标准中很有可能被去除或

prototype的专栏 3658

C++ Metaprogramming::Typelist::Definitions and basic implementations

Version 1.00Author: prototypeCopyright (C) 2004 prototypePermission is granted to copy and redistribute this article provided that its contents (including the title, author information, and this c

prototype的专栏 2534
上一篇: Good tips for being efficient
下一篇: Intel open-sourced a multithread library
prototype
博客等级 码龄25年 9粉丝 10原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址