C++中为什么不要过度参数化

这篇文章主要介绍“C++中为什么不要过度参数化”,在日常操作中,相信很多人在C++中为什么不要过度参数化问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”C++中为什么不要过度参数化”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

创新互联公司专业为企业提供沈阳网站建设、沈阳做网站、沈阳网站设计、沈阳网站制作等企业网站建设、网页设计与制作、沈阳企业网站模板建站服务,10年沈阳做网站经验,不只是建网站,更提供有价值的思路和整体网络服务。

T.61:不要过度参数化成员(SCARY)

Reason(原因)

A member that does not depend on a template parameter cannot be used except for a specific template argument. This limits use and typically increases code size.

不依赖于模板参数的成员无法使用,特定的模板参数除外。这会限制使用并通常会增加代码大小。

Example, bad(反面示例)

template<typename T, typename A = std::allocator{}>
   // requires Regular<T> && Allocator<A>
class List {
public:
   struct Link {   // does not depend on A
       T elem;
       T* pre;
       T* suc;
   };

   using iterator = Link*;

   iterator first() const { return head; }

   // ...
private:
   Link* head;
};

List<int> lst1;
List<int, My_allocator> lst2;

This looks innocent enough, but now Link formally depends on the allocator (even though it doesn't use the allocator). This forces redundant instantiations that can be surprisingly costly in some real-world scenarios. Typically, the solution is to make what would have been a nested class non-local, with its own minimal set of template parameters.

代码看起来足够正确,但是现在Link形式上依赖于分配器(即使它没有使用分配器)。这会引发多余的例示,而这种例示在某些现实流程中可能会带来令人惊讶的高成本。通常的解决方案是让本来的嵌套类别弄成非局部的,同时它的成员只拥有最少的模板参数。

template<typename T>
struct Link {
   T elem;
   T* pre;
   T* suc;
};

template<typename T, typename A = std::allocator{}>
   // requires Regular<T> && Allocator<A>
class List2 {
public:
   using iterator = Link<T>*;

   iterator first() const { return head; }

   // ...
private:
   Link* head;
};

List<int> lst1;
List<int, My_allocator> lst2;

Some people found the idea that the Link no longer was hidden inside the list scary, so we named the technique SCARY. From that academic paper: "The acronym SCARY describes assignments and initializations that are Seemingly erroneous (appearing Constrained by conflicting generic parameters), but Actually work with the Right implementation (unconstrained bY the conflict due to minimized dependencies)."

有些人会发现Link不再被list隐藏,因此我们称这种技术为SCARY。根据大学论文:“SCARY这个缩写描述了一些看起来错误(看起来被冲突的参数约束),但实际上可以和正确的实现一起工作(由于最小化的依赖关系而不会被冲突所限制)的赋值和初始化。”

Enforcement(实施建议)

  • Flag member types that do not depend on every template argument

  • 标记不依赖于任何模板参数的成员

  • Flag member functions that do not depend on every template argument

  • 标记不依赖于任何模板参数的成员的成员函数。

到此,关于“C++中为什么不要过度参数化”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注创新互联网站,小编会继续努力为大家带来更多实用的文章!

网站标题:C++中为什么不要过度参数化
当前路径:https://www.cdcxhl.com/article30/iihiso.html

成都网站建设公司_创新互联,为您提供动态网站网站内链微信小程序静态网站品牌网站制作手机网站建设

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

成都网页设计公司