Paul J. Lucas
Paul J. Lucas

Reputation: 7151

Won't match template function

In:

#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 doesn't match the call to g() because it has 2 template arguments, but it matches h() just fine. Why?

FYI: My codebase actually uses several, highly-specialized string classes, so I want to allow for maximal flexibility where the first and second arguments might be of different string types.

Upvotes: 3

Views: 166

Answers (2)

Puppy
Puppy

Reputation: 147036

g() is rejected because StringType2 is deduced to be a const char[] (or some similar variant of it) that does not offer the c_str() member method. h() matches fine because you forced StringType to be std::string in both cases.

You will need to look into more detailed metaprogramming techniques, but this should be perfectly possible.

Edit: Apparently default args won't participate in template type deduction, or something. In any case, you will need to use a different technique to accomplish this, like partial specialization.

Upvotes: 0

Daniel Gallagher
Daniel Gallagher

Reputation: 7125

The compiler has no idea what StringType2 is supposed to be. You would need to call it with something like:

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

to get it to work correctly.

Upvotes: 7

Related Questions