带有默认参数的模板专业化 [英] Template specialisation with default argument
问题描述
我有一个如下程序.有一个基本模板struct X
和SFINAE的部分专业化版本.
I have a program that is as follows. There is a base template struct X
and a partial specialisation with SFINAE.
template <typename T, typename U = void>
struct X{
X() {
std::cout << "in 1" << std::endl;
};
};
template <typename T>
struct X< T, std::enable_if_t<std::is_integral_v<T>> > {
X() {
std::cout << "in 2" << std::endl;
};
};
int main() {
X<int> x;
}
运行程序时,将打印in 2
.
When running the program in 2
is printed.
-
为什么选择第二个专业而不是第一个专业,因为它们都有效地声明了
struct X<int, void>
.是什么使std::enable_if_t<std::is_integral_v<T>>
比基本模板中显示的默认模板类型参数更专业?
Why is it that the second specialization is chosen over the first since both of them effectively declare a
struct X<int, void>
. What makesstd::enable_if_t<std::is_integral_v<T>>
more specialized than a default template type argument as shown in the base template?
为什么基本模板的默认类型参数必须与要调用的部分专业化和要打印的in 2
的部分专业化定义的类型相同.
为什么更改为std::enable_if_t<std::is_integral_v<T>, bool>
会导致调用基本模板in 1
?
Why does the default type argument of the base template have to be the same as the type defined by the partial specialization for the partial specialization to be called and in 2
to be printed.
Why does changing to std::enable_if_t<std::is_integral_v<T>, bool>
cause the base template in 1
to be called?
推荐答案
The answers to your questions lie in Template Partial Ordering. This is the mechanism the compiler uses to determine which template is the best fit (be it a function template overload, or in your case, a class template specialization).
简而言之,您的通用模板实现具有2个参数T
和U
,而SFINAE专业化仅具有T
参数,而第二个则是从T
推导出来的.因此,它比一般情况下更加专业,最后,当您引用X<int, void>
时,便选择了专业化.
In brief, your generic template implementation has 2 parameters T
and U
, whereas your SFINAE specialization have only the T
parameter, while the second is deduced from T
. It is therefore more specialized than the general case and in the end, when you refer to X<int, void>
, the specialization is chosen.
现在的问题2.假设我们将enable_if
参数替换为bool
而不是void
.现在我们的专业化将是X<int, bool>
而不是X<int, void>
,因此当您引用X<int>
时,即X<int, void>
,它不再与该专业化匹配,因为它们是2种不同的类型.
Now question 2. Suppose we replace the enable_if
parameter with bool
instead of void
. Now our specialization will be X<int, bool>
instead of X<int, void>
, so when you refer to X<int>
, i.e. X<int, void>
, it doesn't match the specialization anymore because those are 2 different types.
这篇关于带有默认参数的模板专业化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!