Sign in to follow this  
Daggerbot

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

Recommended Posts

Daggerbot    127
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]; 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.

Share this post


Link to post
Share on other sites
CmpDev    100
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

Share this post


Link to post
Share on other sites
rip-off    10979
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);
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this