Why do two functions have the same address?

后端 未结 3 546
小鲜肉
小鲜肉 2020-12-02 02:09

Consider this function template:

template
unsigned long f(void *) { return 0;}

Now, I print the addresses of f

3条回答
  •  执念已碎
    2020-12-02 02:33

    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.

提交回复
热议问题