問題描述
考慮這個函數模板:
template<typename T>
unsigned long f(void *) { return 0;}
現在,我將 f
和 f
的地址打印為:
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.
這篇關于為什么兩個函數的地址相同?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!