C++核心准则T.121:模板元编程主要用于模仿概念

时间:2022-07-26
本文章向大家介绍C++核心准则T.121:模板元编程主要用于模仿概念,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

T.121: Use template metaprogramming primarily to emulate concepts

T.121:模板元编程主要用于模仿概念

Reason(原因)

Until concepts become generally available, we need to emulate them using TMP. Use cases that require concepts (e.g. overloading based on concepts) are among the most common (and simple) uses of TMP.

在概念普遍可用之前,我们需要使用TMP模仿它们。需要概念的使用场景(例如基于概念的重载)就在更加普通(和简单的)TMP的用法中。

Example(示例)

template<typename Iter>
    /*requires*/ enable_if<random_access_iterator<Iter>, void>
advance(Iter p, int n) { p += n; }

template<typename Iter>
    /*requires*/ enable_if<forward_iterator<Iter>, void>
advance(Iter p, int n) { assert(n >= 0); while (n--) ++p;}
Note(注意)

Such code is much simpler using concepts:

上述代码如果使用概念会简单很多:

void advance(RandomAccessIterator p, int n) { p += n; }

void advance(ForwardIterator p, int n) { assert(n >= 0); while (n--) ++p;}

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#t121-use-template-metaprogramming-primarily-to-emulate-concepts