最近读到一段代码,大致如下:
1 |
|
由于对C++ Template Metaprogramming 不是很熟悉, 觉得在用GetNext的时候,两个申明都可能会匹配上,那么compiler怎么知道选择哪个呢。
经过一番查找,我才是道这是Partial Template Specialization(偏特化)。举个例子
1 |
|
除了偏特化,还有全特化explicit (full) template specialization. 例子如下:
1 |
|
那么在有多个偏特化的情况下,当实例化的时候,compiler到底是如何做出选择的呢? Rule如下:
-
If only one specialization matches the template arguments, that specialization is used
-
If more than one specialization matches, partial order rules are used to determine which specialization is more specialized. The most specialized specialization is used, if it is unique (if it is not unique, the program cannot be compiled)
-
If no specializations match, the primary template is used
For more detail, please see cppreference.