本篇内容主要讲解“C++的模板概念怎么使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“C++的模板概念怎么使用”吧!
T.41:在模板概念中只对本质属性定义需求
Keep interfaces simple and stable.
维持接口的简单和稳定。
Example (using TS concepts)(示例(使用TS概念))
Consider, a sort instrumented with (oversimplified) simple debug support:
考虑一种包含(过于简单了)简单的调试功能的排序处理:
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:
应该这样写:
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.
很难决定类型的那个属性是本质的,那个属性不是本质的。
到此,相信大家对“C++的模板概念怎么使用”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。