Why do two functions have the same address?

Consider this function template:

template<typename T> unsigned long f(void *) { return 0;} 

Now I print the addresses 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 it is compiled in MSVS10? Are they not two different functions and therefore must print different addresses?

Updated:

I realized that on ideone it prints a different address. MSVS10 optimizes the code, since the function does not depend on T , therefore it produces the same function. @Mark's answer and comments on this are valuable. :-)

+6
c ++ function templates memory-address function-templates
Feb 17 '12 at 5:17
source share
3 answers

Since the function is independent of the template parameter, the compiler can condense all instances into one function.

I do not know why you get 1 for the address.




Added by Nawaz :

I experimented with my real code and came to the conclusion that what @Mark said above is very important here:

Since the function is independent of the template parameter, the compiler can condense all instances into one function.

I also came to the conclusion that if the body function depends on T* , and not on T , it still produces the same function for different type arguments in my real code (but not on ideon). However, if it depends on T , then it creates different functions, because sizeof(T) is different (fortunately for me) for different type arguments.

So, I added a dummy automatic variable of type T to the function template so that the function could depend on the size of T to force it to create different functions.

+2
Feb 17 '12 at 5:20
source share

You need to specify void * :

 std::cout << (void*)(ftype*)f<A> << std::endl; std::cout << (void*)(ftype*)f<B> << std::endl; 

If you apply a pointer to a function (or several other classes of non-pointer pointers), it will be interpreted as a bool operator<< for std::ostream (hence 1 ).

+7
Feb 17 '12 at 5:19
source share

This is just a case of undefined behavior, because the result of casting a pointer to a function is a pointer to an object type of undefined.

A more interesting expression for checking would be f<A> == f<B> , which should be evaluated to true if and only if A and B are of the same type.

+1
Feb 17 2018-12-12T00:
source share



All Articles