问题描述
在C ++ 03中,模板参数扣除在一些上下文中不会发生。例如:
In C++03, template parameter deduction does not occur in some contexts. For example:
template <typename T> struct B {};
template <typename T>
struct A
{
typedef B<T> type;
};
template <typename T>
void f(typename A<T>::type);
int main()
{
B<int> b;
f(b); // ERROR: no match
}
这里, int
不会推导出 T
,因为嵌套类型如 A< T> :: type
是一个非推导的上下文。
Here, int
is not deduced for T
, because a nested type such as A<T>::type
is a non-deduced context.
如果我写了这样的函数:
Had I written the function like this:
template <typename T> struct B {};
template <typename T>
void f(B<T>);
int main()
{
B<int> b;
f(b);
}
一切都很好,因为 B< T& code> 是一个推导的上下文。
everything is fine because
B<T>
is a deduced context.
然而,在C ++ 11中,模板别名可用于伪装嵌套类型在语法类似于第二个例子。例如:
In C++11, however, template aliases can be used to disguise a nested type in syntax similar to the second example. For example:
template <typename T> struct B {};
template <typename T>
struct A
{
typedef B<T> type;
};
template <typename T>
using C = typename A<T>::type;
template <typename T>
void f(C<T>);
int main()
{
B<int> b;
f(b);
}
在这种情况下模板参数扣除是否有效?换句话说,模板别名是一个推导的上下文还是一个非推导的上下文?
Would template argument deduction work in this case? In other words, are template aliases a deduced context or a non-deduced context? Or do they inherit the deduced/non-deduced status of whatever they alias?
推荐答案
它们可以推演为等效代码,而不使用模板别名。例如
They are as deducible as the equivalent code without using template aliases. For example
template<typename T>
using ref = T&;
template<typename T>
void f(ref<T> r);
现在您可以调用
f(x)
和 T
将被完全推断。在 f
的定义时间, ref< T>
被类型
。 T&
是一个推导的上下文。
Now you can call
f(x)
and T
will be deduced perfectly fine. At the definition time of f
already, ref<T>
is replaced by type T&
. And T&
is a deduced context.
在您的情况下,
C< T>
被 typename A< T& :type
,这是 T
的非推演上下文,因此 T
In your case
C<T>
is replaced by typename A<T>::type
, and that is a non-deduced context for T
, so T
cannot be deduced.
这篇关于模板别名如何影响模板参数的扣除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!