Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How template function chooses parameter?

Tags:

c++

templates

#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" );
}

Observation:

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> 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?

Thank you

like image 513
q0987 Avatar asked Oct 01 '14 13:10

q0987


1 Answers

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));

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

Func(std::endl<char, std::char_traits<char>>);
like image 178
Kerrek SB Avatar answered Sep 20 '22 10:09

Kerrek SB