模板推导和重载

问题描述 投票:1回答:2

这是Primer c ++ 5th中的练习:

template <typename T> void f(T);                   //1
template <typename T> void f(const T*);            //2
template <typename T> void g(T);                   //3
template <typename T> void g(T*);                  //4
int i = 42, *p = &i;
const int ci = 0, *p2 = &ci;
g(42); g(p); g(ci); g(p2);
f(42); f(p); f(ci); f(p2);

这是答案:

g(42);  //type: int(rvalue) call template 3  T: int          instantiation: void g(int)
g(p);   //type: int *       call template 4  T: int          instantiation: void g(int *)
g(ci);  //type: const int   call template 3  T: const int    instantiation: void g(const int)
g(p2);  //type: const int * call template 4  T: const int    instantiation: void g(const int *)
f(42);  //type: int(rvalue) call template 1  T: int          instantiation: void f(int)
f(p);   //type: int *       call template 1  T: int *        instantiation: void f(int *)
f(ci);  //type: const int   call template 1  T: const int    instantiation: void f(const int)
f(p2);  //type: const int * call template 2  T:int          instantiation: void f(const int *)

我的问题是为什么f(p)赞成f(T)而不是f(const T *)的实例化

c++ templates
2个回答
1
投票

简而言之,在重载解析中包含函数模板的规则是:

  1. 名称查找确定一组可见的函数,对象和函数模板。
  2. 集合中的每个函数模板从任何显式参数,演绎和/或默认模板参数确定其模板参数,并且如果可能,将替换这些参数以获得一个特定的具体函数签名。 (当不可能时,函数模板只是被抛出集合。当模板参数推断失败时,以及当将参数替换为签名失败时,也可能发生这种情况,即“SFINAE”规则。)
  3. 使用正常的重载决策规则对函数进行比较,将来自模板的签名视为普通的非模板函数。
  4. 只有当步骤3认为其中两个功能不明确时,这些断路器才适用: 一个。如果一个函数签名来自模板而另一个没有,则非模板函数被认为更好。 湾如果两个函数签名都来自模板,并且一个模板比另一个模板“更专业”,则更专业的模板被认为更好。 (简而言之,“更专业”意味着我们可以证明更专业模板的任何有效参数也是不太专业化的模板的有效参数,但反之亦然。)

在此示例的f(p)表达式中,在步骤2中,模板#1推导出T=int*,模板#2推导出T=int,因此签名为:

void f(int*);        // from 1
void f(const int*);  // from 2

在第3步中,参数p的类型为int*,因此来自#1的void f(int*);使用Identity转换(精确匹配),而来自#2的void f(const int*);使用指针转换,因此来自#1的void f(int*);获胜,并且该函数模板专门化是一个名字。

模板#2 void f(const T*);比模板#1 void f(T);更专业。但是,由于第3步确定了答案,我们从未进入第4步,所以这并不重要。 (步骤4的确用于另一个表达式f(p2)。)


0
投票

这不是的答案,但基本上:

f(T)T=int*完全匹配int*

f(T const*)T=int并不完全匹配int*

完全匹配胜利。

© www.soinside.com 2019 - 2024. All rights reserved.