Will not match the template function

AT:

#include <string>

void f( char const*, char const* = "" ) {
}

template<class StringType1,class StringType2> inline
void g( StringType1 const &s1, StringType2 const &s2 = "" ) {
  f( s1.c_str(), s2.c_str() );
}

template<class StringType> inline
void h( StringType const &s1, StringType const &s2 = "" ) {
  f( s1.c_str(), s2.c_str() );
}

int main() {             
  std::string s;
  g( s ); // error: no matching function for call to ‘g(std::string&)’
  h( s ); // OK
  return 0;
}

the compiler does not match the call g()because it has 2 template arguments, but it matches perfectly h(). Why?

FYI: my code base actually uses several highly specialized string classes, so I want to allow maximum flexibility when the first and second arguments can have different types of strings.

+3
source share
2 answers

The compiler does not know what it is StringType2. You will need to call it something like:

   g<std::string, std::string>( s );

to make it work correctly.

+7
source

g() , StringType2 const char [] ( - ), c_str(). h() , StringType std::string.

, .

: -, - . , , , .

0

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


All Articles