模板功能如何选择参数? [英] How template function chooses parameter?
问题描述
#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
但是一个函数指针。
1> Without void Func( std::ostream & ( *manip )( std::ostream & ) )
, the line Func( endl );
will cause compiler errors. I assume the issue is due to the template function void Fun( const T& val )
can ONLY take a type of T
but a function pointer.
2>没有 void Func(const char * p)
c $ c> Func(aaa); 运行良好。我假设原因是类型 T
可以是 const char *
。
2> Without void Func( const char* p )
, the line Func( "aaa" );
runs fine. I assume the reason is that the type T
can be const char*
.
问题>这些是正确的参数吗?
Question> Are these correct arguments?
谢谢
推荐答案
std :: endl
本身就是一个函数模板,因此你不能对 Func
除非您实际上指定了函数。以下应适用:
std::endl
is itself a function template, so you cannot have template argument deduction for Func
unless you actually specify a function. The following should work:
Func(static_cast<std::ostream&(&)(std::ostream&)>(std::endl));
另一种方式(感谢@ 0x499602D2)是指定模板参数:
Another way (thanks to @0x499602D2) is to specify the template arguments:
Func(std::endl<char, std::char_traits<char>>);
这篇关于模板功能如何选择参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!