使用typename参数时,模板参数推导/替换失败 [英] Template argument deduction/substitution failed, when using typename argument

查看:81
本文介绍了使用typename参数时,模板参数推导/替换失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,该代码定义了模板结构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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆