Why do two functions have the same address?

青春壹個敷衍的年華 提交于 2019-11-27 09:43:22
Mark Ransom

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 1 for 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 on T, it still produces the same function for different type arguments in my real code (not on ideone, though). However, if it depends on T, then it produces different functions, because sizeof(T) differs (fortunately for me) for different type arguments.

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

You need to cast to void *:

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

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

This is simply a case of undefined behavior because the results of casting a pointer to a function to a pointer to object type are undefined.

A more interesting expression to examine would bef<A> == f<B> which should evaluate to true if and only if A and B refer to the same type.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!