T.65: Use tag dispatch to provide alternative implementations of a function使用标签分发提供函数的不同实现
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 的简化版本(忽略非连续序列)
C++
structpod_tag{};structnon_pod_tag{};template<classT>structcopy_trait{usingtag=non_pod_tag;};// T is not "plain old data"template<>structcopy_trait<int>{usingtag=pod_tag;};// int is "plain old data"template<classIter>Outcopy_helper(Iterfirst,Iterlast,Iterout,pod_tag){// use memmove}template<classIter>Outcopy_helper(Iterfirst,Iterlast,Iterout,non_pod_tag){// use loop calling copy constructors}template<classIter>Outcopy(Iterfirst,Iterlast,Iterout){returncopy_helper(first,last,out,typenamecopy_trait<Iter>::tag{})}voiduse(vector<int>&vi,vector<int>&vi2,vector<string>&vs,vector<string>&vs2){copy(vi.begin(),vi.end(),vi2.begin());// uses memmovecopy(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:
当概念可以被普遍使用时,这样的选则可以直接区分:
C++
template<classIter>requiresPod<Value_type<iter>>Outcopy_helper(In,first,Inlast,Outout){// use memmove}template<classIter>Outcopy_helper(In,first,Inlast,Outout){// use loop calling copy constructors}