前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则T.65:使用标签分发提供函数的不同实现

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

作者头像
面向对象思考
发布2020-09-21 14:25:19
9230
发布2020-09-21 14:25:19
举报

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<class T> struct copy_trait { using tag = non_pod_tag; };   // T is not "plain old data"

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

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

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

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

void use(vector<int>& vi, vector<int>& vi2, vector<string>& vs, vector<string>& 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<class Iter>
    requires Pod<Value_type<iter>>
Out copy_helper(In, first, In last, Out out)
{
    // use memmove
}

template<class Iter>
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

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Enforcement(实施建议)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档