[c++ templates] weird lack of an error!

Started by
1 comment, last by rip-off 15 years, 5 months ago
Apparently C++ (or at least G++) has a feature I was unaware of. Let's say I have a template function called GetStringLength:
template< typename C >
int GetStringLength( const C* string )
{
  register int i;
  for( i = 0; string; i++ );
  return i;
}
In my code I accidentally made multiple calls to this function using char strings and wchar_t strings without specifying the type for the 'C' tparam, but it seems to have chosen the correct type for me. Here's an example:
int main()
{
  char*    string1 = "hahaha";     //6
  wchar_t* string2 = L"oh nos!!!"; //9

  cout << GetStringLength( string1 ) << endl;
  cout << GetStringLength( string2 ) << endl;

  return 0;
}
I would expect to get an error, as there is no <char> or <wchar_t> following GetStringLength, but instead the program outputs "6" and "9". These are the results I would want, but I expected a compiler error. Is this a C++ standard? Any help is appreciated.
Advertisement
There is nothing weird about it as it is totally standard correct. The template parameter C will be char or wchar_t depending on the input parameter.
Could you explain why are you using the register keyword here and what you hope it will gain you?
http://www.parashift.com/c++-faq-lite/templates.html#faq-35.3
This is expected. Where it can C++ will deduce the template parameters in template functions. This doesn't apply to template classes however.

As an example, the type std::pair<A,B> can be constructed like so:
std::pair<A,B>(a,b)

However, we can use the utility function std::make_pair()
std::make_pair(a,b)

This is good because typically the type names are going to be a good bit longer. In addition if we were change the types then we don't need to change the call.

An example of where C++ would fail to deduce the template type is:
template< typename T >void pointer_hackery( const T *t ){    if(t)    {        // ...    }}int main(){    // call with a NULL pointer    // poor compiler can't figure out what T is.    pointer_hackery(0);}

This topic is closed to new replies.

Advertisement