2012-11-09 59 views
6
template<typename T> 
void print_size(const T& x) 
{ 
    std::cout << sizeof(x) << '\n'; 
} 

int main() 
{ 
    print_size("If you timidly approach C++ as just a better C or as an object-oriented language, you are going to miss the point."); 
    // prints 115 
} 

這將在最近的g ++編譯器上打印115。顯然,T被推斷爲一個數組(而不是指針)。這種行爲是否由標準保證?我有點驚訝,因爲下面的代碼打印了指針的大小,我認爲auto的行爲完全像模板參數演繹?字符串文字的模板參數推導

int main() 
{ 
    auto x = "If you timidly approach C++ as just a better C or as an object-oriented language, you are going to miss the point."; 
    print_size(x); 
    // prints 4 
} 
+1

不要現在爲前者,但後者並不意外。字符串文字是數組,不是嗎? – Tomek

+2

對於讀這個的人不知道:你不能通過值傳遞數組(它們衰減爲指針),但是你確實可以傳遞一個對數組的引用。在這裏,'const T&'成爲一個數組的引用,所以'sizeof'給出數組的大小。 –

+1

Martinho的答案涵蓋了主要問題。對於保證的行爲,14.8.2.1/2:「如果'P'不是引用類型:如果'A'是一個數組類型,則使用由數組到指針標準轉換產生的指針類型來代替'A'用於類型推導; ...「其中'P'是模板函數的函數參數的類型,可以涉及一個或多個模板參數,'A'是函數調用中使用的表達式的類型。 – aschepler

回答

8

auto行爲完全像模板參數推導。完全像T

比較:

template<typename T> 
void print_size(T x) 
{ 
    std::cout << sizeof(x) << '\n'; 
} 

int main() 
{ 
    print_size("If you timidly approach C++ as just a better C or as an object-oriented language, you are going to miss the point."); 
    // prints 4 
    auto x = "If you timidly approach C++ as just a better C or as an object-oriented language, you are going to miss the point."; 
    print_size(x); 
    // prints 4 
} 

有了這個:

template<typename T> 
void print_size(const T& x) 
{ 
    std::cout << sizeof(x) << '\n'; 
} 

int main() 
{ 
    print_size("If you timidly approach C++ as just a better C or as an object-oriented language, you are going to miss the point."); 
    // prints 115 
    const auto& x = "If you timidly approach C++ as just a better C or as an object-oriented language, you are going to miss the point."; 
    print_size(x); 
    // prints 115 
} 

不完全是,但是這不是極端案例之一。

+0

愚蠢的我。感謝您解除窗簾:) – fredoverflow

+0

因爲當然,您不能將C風格的數組作爲C++中的值傳遞。 – Yakk

+0

@Yakk:的確,這會破壞C兼容性。 C沒有引用,所以現在沒有任何行爲可以打破。 – MSalters