为什么两个函数的地址相同?

考虑这个函数模板:

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

现在,我将 ff 的地址打印为:

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;

如果在 MSVS10 中编译,为什么它们打印相同的地址?它们不是两个不同的功能,因此应该打印不同的地址吗?

Why do they print the same address if compiled in MSVS10? Are they not two different functions and therefore should print different addresses?

更新:

我意识到在 ideone 上,它会打印不同的地址.MSVS10 优化了代码,因为该函数不以任何方式依赖 T,因此它产生相同的函数.@Mark 对此的回答和评论很有价值.:-)

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.

我不知道你为什么得到 1 作为地址.

I don't know why you get 1 for the address.

我用我的真实代码进行了试验,并得出结论,@Mark 上面所说的在这里非常重要:

I experimented with my real code, and concluded that what @Mark said above is very important here :

由于函数不依赖于模板参数,编译器可以将所有实例化为一个函数.

我还得出一个结论,如果函数体依赖于T*,而不是T,它仍然为我的不同类型参数生成相同的函数真正的代码(虽然不是在 ideone 上).然而,如果它依赖于 T,那么它会产生不同的函数,因为 sizeof(T) 对于不同的类型参数是不同的(对我来说很幸运).

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.

所以我在函数模板中添加了一个 T 类型的虚拟 automatic 变量,这样函数就可以依赖于 T 的大小从而强制它产生不同的功能.

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.

相关文章