Jump to content
  • Advertisement
Sign in to follow this  
Daggerbot

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

This topic is 3526 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


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

Share this post


Link to post
Share on other sites
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!