Consider this function template:
template<typename T>
unsigned long f(void *) { return 0;}
Now, I print the addresses of f<A> and f<B> as:
std::cout << (void*)f<A> << std::endl;
std::cout << (void*)f<B> << std::endl;
Why do they print the same address if compiled in MSVS10? Are they not two different functions and therefore should print different addresses?
Updated:
I realized that on ideone, it prints the different address. MSVS10 optimizes the code, as the function doesn’t depend on T in any way, so it produces same function. @Mark’s answer and comments on this are valuable. 🙂
Since the function doesn’t depend on the template parameter, the compiler can condense all instantiations into a single function.
I don’t know why you get
1for the address.Added by Nawaz:
I experimented with my real code, and concluded that what @Mark said above is very important here :
Since the function doesn’t depend on the template parameter, the compiler can condense all instantiations into a single function.
I also came to a conclusion that if the function-body depends on
T*, not onT, it still produces the same function for different type arguments in my real code (not on ideone, though). However, if it depends onT, then it produces different functions, becausesizeof(T)differs (fortunately for me) for different type arguments.So I added a dummy automatic variable of type
Tin the function template, so that the function could depend on the size ofTso as to force it to produce different functions.