關於下面的代碼,編譯器如何選擇調用哪個模板函數? 如果const T &函數被省略,則始終調用T &函數。 如果省略T &功能,則始終調用const T &函數。 如果兩者都包含在內,則結果如下。編譯如何選擇調用哪個模板函數?
#include <iostream>
#include <typeinfo>
template <typename T>
void function(const T &t)
{
std::cout << "function<" << typeid(T).name() << ">(const T&) called with t = " << t << std::endl;
}
template <typename T>
void function(T &t)
{
std::cout << "function<" << typeid(T).name() << ">(T&) called with t = " << t << std::endl;
}
int main()
{
int i1 = 57;
const int i2 = -6;
int *pi1 = &i1;
int *const pi3 = &i1;
const int *pi2 = &i2;
const int *const pi4 = &i2;
function(pi1); ///just a normal pointer -> T&
function(pi2); ///cannot change what we point to -> T&
function(pi3); ///cannot change where we point -> const T&
function(pi4); ///cannot change everything -> const T&
return 0;
}
/* g++ output:
function<Pi>(T&) called with t = 0x22cd24
function<PKi>(T&) called with t = 0x22cd20
function<Pi>(const T&) called with t = 0x22cd24
function<PKi>(const T&) called with t = 0x22cd20
*/
/* bcc32 output:
function<int *>(T&) called with t = 0012FF50
function<const int *>(T&) called with t = 0012FF4C
function<int *>(const T&) called with t = 0012FF50
function<const int *>(const T&) called with t = 0012FF4C
*/
/* cl output:
function<int *>(T&) called with t = 0012FF34
function<int const *>(T&) called with t = 0012FF28
function<int *>(const T&) called with t = 0012FF34
function<int const *>(const T&) called with t = 0012FF28
*/
一個小技巧,當你碰巧使用G ++是。 '__PRETTY_FUNCTION__'提供了一個格式良好的字符串來描述你的函數,包括模板參數類型[「int *」而不是「Pi」]。在學習模板如何工作時,我發現這是非常寶貴的,因爲在g ++下'typeid(T).name()'的默認行爲是相當神祕的。我相信'__FUNCSIG__'在VS下提供了類似的功能,但我無法訪問它進行驗證。 – 2010-04-25 17:16:43