Public Group

# Struggling with Templates

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

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

1. 1
2. 2
Rutin
18
3. 3
4. 4
5. 5
frob
13

• 16
• 9
• 31
• 16
• 9
• ### Forum Statistics

• Total Topics
632613
• Total Posts
3007430

×