模板演绎似乎是错误的
Template deduction seems wrong
模板推导似乎不对,为什么叫(c)而不是(b)?
#include <iostream>
using namespace std;
template<class T> void f(T){cout << "f(T)";}//(a)
template<> void f<>(int*){cout << "f(int*)";}//(b)
template<class T> void f(T*){cout << "f(T*)";}//(c)
//void f(int*){cout <<"POD:f(int*)";}//(d)
int main(int argc,char*argv[])
{
int p = 1;
f(&p);
cout <<endl;
return 0;
}
输出:
f(T*)
好吧,让我们先理清头绪。
(a)是一个函数模板。(b)是该函数模板的专门化。(c)是重载(a)的另一个函数模板。
当你写f(&p)
时,有两个重载要考虑:两个函数模板,(a)和(c)。(c)中T*
比(a)中的T
更专门化,所以(c)被选中。
现在让我们考虑被注释掉的(d),这不是函数模板(a)的专门化,而是额外的重载。为了解决f(&p)
调用,现在有三个重载需要考虑。(d)不是模板,并且int*
与&p
的类型匹配,因此它在其他两个中被选中
模板专门化必须在模板之后。在这里,在您的例子中,它看起来像这样:
template<class T> void f(T){cout << "f(T)";}//(a) // Template 1
template<> void f<>(int*){cout << "f(int*)";}//(b) // Specialization of template 1
template<class T> void f(T*){cout << "f(T*)";}//(c) // Template 2, conceals template 1
因此,得到了模板2的实例化。正确的做法是:
template<class T> void f(T*){cout << "f(T*)";} // Template 1
template<class T> void f(T){cout << "f(T)";} // Template 2
template<> void f<>(int*){cout << "f(int*)";} // Specialization of the template 1
输出:f(int*)
相关文章:
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 尝试将lambda函数放在队列中时出现一般分配器错误(可能是与unique_ptr有关的错误)
- 将错误返回给调用方而不是立即在 C++ 中抛出错误是否是一种好的做法
- 工会成员的析构函数似乎是自动调用的
- 对GLFW / Vulkan的未定义引用,尽管库似乎是链接的
- C++ 编译错误:gnu_printf是无法识别的格式函数类型
- 这个错误可能是什么?ANSI C文件
- C 程序如果功能中的语句不执行.在逻辑上似乎是错误的
- 对于特定情况的整数溢出似乎是由整数溢出引起的错误
- Travis CI似乎是从错误的Stdlib读书
- 我的功能似乎是正确的,但我会收到编译错误
- 这似乎是C Primer第5版中的错误
- 这似乎是 clang++ 编译器中的一个错误
- 我正在收到错误的“ list :: ShowList”:功能风格的初始化器似乎是我的CPP文件中的函数定义'
- libc ++is_copy_constructible对我来说似乎是错误的
- 程序超过了时间限制,这似乎是不可能的——错误代码
- 错误C2448:函数式初始化器似乎是函数定义
- 模板演绎似乎是错误的
- visual C++,错误C2448-函数样式初始值设定项似乎是函数定义
- std::regex_match的结果似乎是错误的