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;
}
Struggling with Templates
I have a question regarding templates.
If you have a container class; can you overload a function like this?
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)?
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement