C++核心准则T.42:使用模板别名简化记法并隐藏实现细节

时间:2022-07-24
本文章向大家介绍C++核心准则T.42:使用模板别名简化记法并隐藏实现细节,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

君子兰

T.42: Use template aliases to simplify notation and hide implementation details

T.42:使用模板别名简化记法并隐藏实现细节

Reason(原因)

Improved readability. Implementation hiding. Note that template aliases replace many uses of traits to compute a type. They can also be used to wrap a trait.

提高可读性。隐藏实现。注意模板别名代替很多用于计算类型特征的使用。它们可以用于封装特征。

Example(示例)

template<typename T, size_t N>
class Matrix {
    // ...
    using Iterator = typename std::vector<T>::iterator;
    // ...
};

This saves the user of Matrix from having to know that its elements are stored in a vector and also saves the user from repeatedly typing typename std::vector<T>::.

Matrix的用户不必知道它的元素存存储于于vector,也让用户不必重复输入类型名std::vecttor<T>::。

Example(示例)

template<typename T>
void user(T& c)
{
    // ...
    typename container_traits<T>::value_type x; // bad, verbose
    // ...
}

template<typename T>
using Value_type = typename container_traits<T>::value_type;

This saves the user of Value_type from having to know the technique used to implement value_types.

Value_type的用户不必了解实现value_type的技术。

template<typename T>
void user2(T& c)
{
    // ...
    Value_type<T> x;
    // ...
}
Note(注意)

A simple, common use could be expressed: "Wrap traits!"

简单,普通的用法可以被解释为“封装特征”。

Enforcement(实施建议)

  • Flag use of typename as a disambiguator outside using declarations.
  • 标记在using外面将typename作为消歧器使用的情况。
  • ???

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#t42-use-template-aliases-to-simplify-notation-and-hide-implementation-details