使用typename参数时,模板参数推导/替换失败 [英] Template argument deduction/substitution failed, when using typename argument
问题描述
我有以下代码,该代码定义了模板结构W
,该结构将基于W
的模板参数导出类型T
:
I have the following code, which defines a template struct W
that exports a type T
that's based on the template argument to W
:
#include <iostream>
using namespace std;
template <unsigned N>
struct Y {};
template <unsigned N>
struct W {
using T = Y<N>;
};
然后,我定义了一个查看此类型T
的模板函数:
I then defined this template function that looks at this type T
:
template <unsigned N>
void foo (const typename W<N>::T& in) {
//--
}
这里的问题是,如果我尝试使用导出为T
的类型之一从main
调用此函数,它将无法编译.例如,如果我写
The problem here is that if I try calling this function from main
using one of the types exported as T
, it doesn't compile. For example, if I write
int main() {
Y<2> y;
foo(y);
return 0;
}
我得到一个编译器错误,提示:
I get a compiler error that says
模板参数推导/替换失败:
template argument deduction/substitution failed:
无法推断出模板参数
这是怎么回事?
推荐答案
C ++编译器无法弄清这一点的原因与模板专业化有关.例如,假设您像这样专门化W
结构模板:
The reason that the C++ compiler can't figure this out has to do with template specialization. For example, suppose that you specialize the W
struct template like this:
template <> struct W<137> {
using T = Y<0>; // Not Y<137>
};
现在,假设您调用foo
,并传入Y<0>
作为参数.编译器应推断为N
的数值是什么?它可能为零,因为W<0>
将T
定义为Y<0>
.但这很容易成为137,因为W<137>
也将T
定义为Y<0>
.
Now, suppose that you call foo
, passing in a Y<0>
as the argument. What should the compiler deduce as the numeric value of N
? It could be zero, since W<0>
defines T
as Y<0>
. But it could just as easily be 137, since W<137>
defines T
as Y<0>
as well.
更一般地,出于上面显示的原因,C ++绝不会尝试根据 inner 类型之一推论出 outer 模板参数的类型.
More generally, C++ will never try to deduce the type of a template argument to an outer template based on one of the inner types, for precisely the reason shown above.
这篇关于使用typename参数时,模板参数推导/替换失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!