Hello everyone!I am a Chinese.So please forgive me my poor English.
Here is my question.
template<typename T>
string debug_rep(const T &t);
We might use this function as follows:
string s("hi");
cout<< debug_rep(&s) << endl;
Which instantiation will be generated?
1.string debug_rep<string*>(string * const&)
2.string debug_rep<string*>(const string*&)
I think the first one will be generated.But on the C++ Primer (5th edition,P696),it says that the function parameter will be const string*&.
Maybe I just took some mistakes.Thank you for telling me where was I wrong!!
#include <iostream>
#include <string>
#include <type_traits>
#include <typeinfo>
template < typename T> std::string debug_rep( const T& arg )
{
static_assert( std::is_same< decltype(arg), std::string* const& >::value, "expcted type of arg to be std::string* const&" ) ;
std::cout << "debug_rep: type of arg is std::string* const&\n" ;
return"" ;
}
template < typename T> std::string debug_rep2( const T& )
{
std::cout << "debug_rep2: generalisation\n" ;
return"" ;
}
using pstr_t = std::string* ;
template <> std::string debug_rep2<pstr_t>( const pstr_t& arg )
{
static_assert( std::is_same< decltype(arg), std::string* const& >::value, "expected std::string* const&" ) ;
std::cout << "debug_rep2: specialisation for std::string* - type of arg is std::string* const&\n" ;
return"" ;
}
int main()
{
std::string s( "hi" ); // type of s is std::string
// type of std::addressof(s) is 'pointer to std::string' ie. std::string*
// type of &s is 'pointer to std::string' ie. std::string*
// using pstr_t = std::string* ; // type pstr_t is 'pointer to std::string' ie. std::string*
debug_rep(&s) ; // instantiate function template std::string debug_rep<X>( const X& arg )
// where the type X is the type of the expression &s
// ie where the type X is pstr_t; std::string debug_rep<pstr_t>( const pstr_t& arg )
// ie. std::string debug_rep( std::string* const& arg );
// type of arg is 'const pointer to (non-cost) std::string' or std::string* const&
debug_rep2(&s) ;
}
Thanks for your detailed answer!
But it's not the same as what <<c++ primer>> says.I'm worried that it will mislead others.I also know that this book is unlikely to take mistakes.I really don't know what I should do.If you were me,what would you do?
All books might contain errors. I believe there was a second printing which should fix most errors. If you have second printing and the error is still here, then it is probably unnoticed. You can submit it here: http://www.informit.com/store/c-plus-plus-primer-9780321714114 (Updates → Submit Errata).