浅墨浓香

想要天亮进城,就得天黑赶路。

导航

第8章 编译期编程:8.3 偏特化的执行路径选择

Posted on 2020-05-16 17:18  浅墨浓香  阅读(242)  评论(0编辑  收藏  举报

8.3 Execution Path Selection with Partial Specialization

8.3 偏特化的执行路径选择

 

An interesting application of a compile-time test such as isPrime() is to use partial specialization to select at compile time between different implementations.

编译期测试(如isPrime())的一个有趣应用,就是使用偏特化在编译期选择不同的模板实现。

For example, we can choose between different implementations depending on whether a template argument is a prime number:

例如,我们可以根据模板参数是否为质数来选择不同的模板实现:

// 主辅助模板:
template<int SZ, bool = isPrime(SZ)>
struct Helper;

//如果 SZ不是质数时的模板实现
template<int SZ>
struct Helper<SZ, false>
{
    ...
};



// SZ为质数时的模板实现:
template<int SZ>
struct Helper<SZ, true>
{
    ...
};

Here, depending on whether the size of the std::array<> argument is a prime number, we use two different implementations of class Helper<>. This kind of application of partial specialization is broadly applicable to select among different implementations of a function template depending on properties of the arguments it’s being invoked for.

这里我们根据std::array<>数组的大小是否为质数来使用Helper<>类模板的两种不同实现。这种偏特化的使用方法,被广泛适用于那些需要根据调用参数属性进行选择不同函数模板实现的场合中。

Above, we used two partial specializations to implement the two possible alternatives. Instead, we can also use the primary template for one of the alternatives (the default) case and partial specializations for any other special case:

上面,我们对两种可能的情况实现了两种特化版本。其实,也可以将基本模板应用于其中一种 (默认) 情况,然后再特化一个版本来代表另一种特殊情况:

// 主辅助模板 (在无合适的偏特化下使用):
template<int SZ, bool = isPrime(SZ)>
struct Helper
{
    ..
};

// SZ为质数的特化实现:
template<int SZ>
struct Helper<SZ, true>
{
    ..
};

Because function templates do not support partial specialization, you have to use other mechanisms to change function implementation based on certain constraints.

由于函数模板不支持偏特化,所以你必须使用其他机制根据特定的约束条件来选择函数的实现。

Our options include the following:

包括以下选项:

  • Use classes with static functions,

  使用有static函数的类,

  • Use std::enable_if, introduced in Section 6.3 on page 98,

  使用第98页6.3节中介绍的std::enable_if,

  • Use the SFINAE feature, which is introduced next, or

  使用下一节将介绍的SFINAE特性,或者

  • Use the compile-time if feature, available since C++17, which is introduced below in Section 8.5 on page 135.

  使用从C++17开始可用的编译期if,这部分内容将在下面的第135页8.5节中介绍。

Chapter 20 discusses techniques for selecting a function implementation based on constraints.

第20章将介绍基于限制条件的模板实现选择技术。