Jump to content
  • Advertisement
Sign in to follow this  
ndwork

Struggling with Templates

This topic is 3621 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

I have a question regarding templates. If you have a container class; can you overload a function like this?
template <class T> static
myContainer<T> myFunc( const myContainer<std::complex<T> > &in ){
  std::cout << "complex" << std::endl;
}

template <class T>
static myContainer<T> myFunc( const myContainer<T> &in ){
  std::cout << "not complex" << std::endl;
}


My intention is effectively to partially specialize. So that for inputs of type myContainer<complex>, the first version of the compiler is called, and for all other inputs, the second version is called. I've done it in my code, and it seems to work. But I don't quite understand. How does the compiler know that 'T' of the second version is not of type std::complex<something>? Or, is this some underfined behavior that happens to work perperly with my compiler (VS2005)?

Share this post


Link to post
Share on other sites
Advertisement
This is defined behavior, and it works as you expect. The standardese goes like this: your two functions are separate function template overloads of the function myFunc(). During overload resolution of the function template, the compiler performs a partial ordering to determine which function is used. Essentially, the compiler determines what T needs to be in each of the template functions, and when it does so, there's a list of type transformations that can be applied. The template the needs the fewest transformations is the one that gets used for overload resolution. So if you call myFunc(myContainer<std::complex<int> >()), the first overload T is int and the second, T is std::complex<int>. The second requires adding a std::complex<> to a basic type, so requires more transformations than the first one, so the first one is used. The complete list of allowed transformations is given in section 14.8.2.4 paragraph 9 of the C++ standard, if you want to look them up.

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.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!