Sign in to follow this  
ndwork

Struggling with Templates

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
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

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