C++核心准则T.65:使用标签分发提供函数的不同实现

面向对象思考

共 2232字,需浏览 5分钟

 ·

2020-09-16 18:29

T.65: Use tag dispatch to provide alternative implementations of a function

T.65:使用标签分发提供函数的不同实现


Reason(原因)

  • A template defines a general interface.

    模板定义普遍接口。

  • Tag dispatch allows us to select implementations based on specific properties of an argument type.

    标签分发允许我们根据参数类型的特定属性选择实现方式。

  • Performance.

    性能



Example(示例)

This is a simplified version of std::copy (ignoring the possibility of non-contiguous sequences)

这是std::copy的简化版本(忽略非连续序列)

struct pod_tag {};
struct non_pod_tag {};

template struct copy_trait { using tag = non_pod_tag; }; // T is not "plain old data"

template<> struct copy_trait { using tag = pod_tag; }; // int is "plain old data"

template
Out copy_helper(Iter first, Iter last, Iter out, pod_tag)
{
// use memmove
}

template
Out copy_helper(Iter first, Iter last, Iter out, non_pod_tag)
{
// use loop calling copy constructors
}

template
Out copy(Iter first, Iter last, Iter out)
{
return copy_helper(first, last, out, typename copy_trait::tag{})
}

void use(vector& vi, vector& vi2, vector& vs, vector& vs2)
{
copy(vi.begin(), vi.end(), vi2.begin()); // uses memmove
copy(vs.begin(), vs.end(), vs2.begin()); // uses a loop calling copy constructors
}

This is a general and powerful technique for compile-time algorithm selection.

这是一个可以在编译时选择算法的普遍和强大的技术。


Note(注意)

When concepts become widely available such alternatives can be distinguished directly:

当概念可以被普遍使用时,这样的选项可以直接区分:

template
requires Pod>
Out copy_helper(In, first, In last, Out out)
{
// use memmove
}

template
Out copy_helper(In, first, In last, Out out)
{
// use loop calling copy constructors
}
Enforcement(实施建议)

???


原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#t65-use-tag-dispatch-to-provide-alternative-implementations-of-a-function


新书介绍

《实战Python设计模式》是作者最近出版的新书,拜托多多关注!

本书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。

对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。




觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!



浏览 17
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报