gpt4 book ai didi

c++ - 需要了解函数模板解析规则

转载 作者:行者123 更新时间:2023-11-30 04:07:58 25 4
gpt4 key购买 nike

我真的对模板重载/特化解析规则的某些细节感到困惑。通过阅读 Herb Sutter on template overloading/specialization 的这篇文章,我试图对这个主题有一些了解。 .我坚持文章中的以下特定点。

在这里

Consider the following code:
// Example 2: Explicit specialization
//
template<class T> // (a) a base template
void f( T );
template<class T> // (b) a second base template, overloads (a)
void f( T* ); // (function templates can't be partially
// specialized; they overload instead)
template<> // (c) explicit specialization of (b)
void f<>(int*);
// ...
int *p;
f( p ); // calls (c)
The result for the last line in Example 2 is just what you'd expect. The question of the day, however, is why you expected it. If you expected it for the wrong reason, you will be very surprised by what comes next. After all, "So what," someone might say, "I wrote a specialization for a pointer to int, so obviously that's what should be called" - and that's exactly the wrong reason.
Consider now the following code, put in this form by Peter Dimov and Dave Abrahams:
// Example 3: The Dimov/Abrahams Example
//
template<class T> // (a) same old base template as before
void f( T );
template<> // (c) explicit specialization, this time of (a)
void f<>(int*);
template<class T> // (b) a second base template, overloads (a)
void f( T* );
// ...
int *p;
f( p ); // calls (b)! overload resolution ignores
// specializations and operates on the base
// function templates only

我看到示例 2 和示例 3 之间的唯一区别是模板 b 和 c 的声明顺序。我不明白为什么这会产生很大的不同。声明的顺序与什么有关?我一定是错过了 C++ 的基本概念,而且我在文章中没有看到对此的解释。

非常感谢有人为我解决这个问题。

谢谢。

最佳答案

What's order of declaration got to do with anything?

特化声明必须始终跟在被特化的模板声明之后 (14.7.3/3)。在示例 2 中,(c) 是 两者 (a) 和 (b) 的显式特化。在示例 3 中,(c) 只是 (a) 的显式特化,因为 (b) 紧随其后。

执行重载决议时,模板是否具有显式特化并不重要。在这两个示例中,重载决策选择模板 (b) 而不是 (a),因为它更专业 (14.5.6.2)。在示例 2 中,实际上选择哪一个并不重要,因为 (c) 是两个模板的特化,因此无论如何都会调用它。在示例 3 中,它确实很重要。因为 (b) 赢得重载决议并且 (c) 不是 (b) 的特化,所以 (c) 不会被调用。

关于c++ - 需要了解函数模板解析规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22124256/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com