How does a template function select a 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" ); } 

Comment:

1> Without void Func( std::ostream & ( *manip )( std::ostream & ) ) string Func( endl ); will cause compiler errors. I suppose the problem is that the function of the void Fun( const T& val ) template void Fun( const T& val ) can ONLY accept the type T , but a pointer to the function.

2> Without void Func( const char* p ) string Func( "aaa" ); works fine. I assume the reason is that the type T can be const char* .

Questions> Are these the right arguments?

thanks

+6
source share
1 answer

std::endl itself is a function template, so you cannot derive a template argument for Func if you did not specify any function. The following should work:

 Func(static_cast<std::ostream&(&)(std::ostream&)>(std::endl)); 

Another way (thanks @ 0x499602D2) is to specify the template arguments:

 Func(std::endl<char, std::char_traits<char>>); 
+8
source

Source: https://habr.com/ru/post/976109/


All Articles