#include <iostream>
#include <ostream>
template<typename T>
void Func(const T& val)
{
std::cout << "const T& val\n";
}
void Func(const char* p)
{
std::cout << "const char * p\n";
}
void Func(std::ostream & (*manip)(std::ostream &))
{
std::cout << "ostream\n";
}
int main()
{
Func(std::endl);
Func("aaa");
}
观察:模板函数如何选择参数?
1>没有void Func(std::ostream & (*manip)(std::ostream &))
,行Func(endl);
会导致编译器错误。我认为这个问题是由于模板函数void Fun(const T& val)
只能使用T
类型的函数指针。
2>不void Func(const char* p)
,线Func("aaa");
运行正常。我假设原因是类型T
可以是const char*
。
问题>这些是正确的参数?
谢谢
是第一功能真的叫乐趣,而不是Func键,或者是一个错字? – happydave 2014-10-01 13:53:57
@happydave,我修改了代码和问题。 – q0987 2014-10-01 13:55:07
在没有const char *重载的第二种情况下,T被推断为char [4]。 – 2014-10-01 14:02:59