c++ - 模板参数推导失败

标签 c++ templates

我编写了以下模板参数推导失败的代码:

template<int>
struct num {};

template<int m>
void match(num<2*m>) {
}

int main()
{
  match(num<2>());
  return 0;
}

我凭直觉知道编译器无法推断出正确的 m,但我想了解其失败原因的理论基础。谁能解释一下?

最佳答案

好吧,您基本上是在要求编译器求解方程 2 * m == 2为您确定模板参数 m对于 match .编译器不会在模板参数推导过程中求解方程式,无论它们多么简单和明确。

14.8.2.4/14 (C++03)、14.8.2.5/16 (C++11) 中的语言规范涵盖了您的情况并有类似的示例

14 If, in the declaration of a function template with a non-type template-parameter, the non-type template-parameter is used in an expression in the function parameter-list, the corresponding template-argument must always be explicitly specified or deduced elsewhere because type deduction would otherwise always fail for such a template-argument.

template<int i> class A { /* ... */ };
template<short s> void g(A<s+1>);

void k() {
  A<1> a;
  g(a); //error: deduction fails for expression s+1
  g<0>(a); //OK
}

至于为什么这样做...我认为很明显,在一般情况下,求解数学方程式的问题太复杂了。它还可能导致模棱两可的解决方案或不属于预期域的解决方案。例如,对于 match(num<3>()),您希望编译器推断出什么? ?

关于c++ - 模板参数推导失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13596728/

相关文章:

c++ - 基于整体类模板专门化一个类方法

c++ - 概念同时执行循环

c++ - 如何使用 boost 函数来转换参数类型?

c++ - 函数属性是否继承?

javascript - 如何在 Genshin 中呈现 javascript 模板?

c++ - std::apply 到模板函数中的构造函数

c++ - 如何根据模板参数更改值?

c++ - 以错误的顺序运行包含大量 INSERT 语句和一个 SELECT 语句的查询

c++ - CGAL组合 map 和Geomview

c++ - 自定义 vector 模板 - 字符串