前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则T.41:在模板概念中只对本质属性定义需求​

C++核心准则T.41:在模板概念中只对本质属性定义需求​

作者头像
面向对象思考
发布2020-09-10 10:27:15
4150
发布2020-09-10 10:27:15
举报
文章被收录于专栏:C++核心准则原文翻译

T.41: Require only essential properties in a template's concepts

T.41:在模板概念中只对本质属性定义需求

Reason(原因)

Keep interfaces simple and stable.

维持接口的简单和稳定。

Example (using TS concepts)(示例(使用TS概念))

Consider, a sort instrumented with (oversimplified) simple debug support:

考虑一种包含(过于简单了)简单的调试功能的排序处理:

代码语言:javascript
复制
void sort(Sortable& s)  // sort sequence s
{
    if (debug) cerr << "enter sort( " << s <<  ")\n";
    // ...
    if (debug) cerr << "exit sort( " << s <<  ")\n";
}

Should this be rewritten to:

应该这样写:

代码语言:javascript
复制
template<Sortable S>
    requires Streamable<S>
void sort(S& s)  // sort sequence s
{
    if (debug) cerr << "enter sort( " << s <<  ")\n";
    // ...
    if (debug) cerr << "exit sort( " << s <<  ")\n";
}

After all, there is nothing in Sortable that requires iostream support. On the other hand, there is nothing in the fundamental idea of sorting that says anything about debugging.

毕竟Sortable中没有任何需要iostream支持的东西。同样,排序的基本想法中也没有任何关于调试的需求。

Note(注意)

If we require every operation used to be listed among the requirements, the interface becomes unstable: Every time we change the debug facilities, the usage data gathering, testing support, error reporting, etc., the definition of the template would need change and every use of the template would have to be recompiled. This is cumbersome, and in some environments infeasible.

如果我们要求所有用到的操作都被罗列在需求中,接口的可用性就会降低:每次我们改变调试功能,用法数据收集,测试支持,错误报告,等等,模板的定义都需要修改,并且每个使用模板的代码都必须重新编译。这种方式很笨拙,在某些环境中也是无法做到的。

Conversely, if we use an operation in the implementation that is not guaranteed by concept checking, we may get a late compile-time error.

相反,如果我们使用某个没有被概念检查保证的实现中的操作,我们可能得到迟到的编译时错误。

By not using concept checking for properties of a template argument that is not considered essential, we delay checking until instantiation time. We consider this a worthwhile tradeoff.

通过不用概念检查非本质模板参数的属性,我们将检查延迟到实例化时。我们认为这是一种值得的妥协。

Note that using non-local, non-dependent names (such as debug and cerr) also introduces context dependencies that may lead to "mysterious" errors.

注意,使用非局部,独立名称(例如debug和cerr)也会引入可能导致“神秘”错误的上下文依赖。

Note(注意)

It can be hard to decide which properties of a type are essential and which are not.

很难决定类型的那个属性是本质的,那个属性不是本质的。

Enforcement(实施建议)

???

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#t41-require-only-essential-properties-in-a-templates-concepts

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-09-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • T.41: Require only essential properties in a template's concepts
  • Reason(原因)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档