2013-04-19 107 views
0

我有一些重載函數,但在我的測試代碼中產生了一些錯誤。重載函數產生模糊錯誤

inline void tt(uint8_t& v) { } 
inline void tt(int8_t& v) { } 
inline void tt(char& v) { } 
inline void tt(uint16_t& v) { } 
inline void tt(int16_t& v) { } 
inline void tt(uint32_t& v) { } 
inline void tt(int32_t& v) { } 
inline void tt(uint64_t& v) { } 
inline void tt(int64_t& v) { } 

int main(int argc, char* argv[]) { 
    unsigned char t1; 
    signed char t2; 
    unsigned short t3; 
    short t4; 
    unsigned int t5; 
    int t6; 
    unsigned long t7; 
    long t8; 
    char t9; 

    tt(t1); // ok 
    tt(t2); // ok 
    tt(t3); // ok 
    tt(t4); // ok 
    tt(t5); // ok 
    tt(t6); // ok 
    tt(t7); // error 
    tt(t8); // error 
    tt(t9); // ok 
} 

爲什麼所有工作除(無符號)長?看在standard長是至少(像所有其他類型)32位。

There are five standard signed integer types: 「signed char」, 「short int」, 「int」, 「long int」, and 「long long int」. In this list, each type provides at least as much storage as those preceding it in the list.

我可以通過插入

inline void tt(unsigned long int& v) { } 
inline void tt(long int& v) { } 

到代碼避免這種情況。我只想知道爲什麼這個演員不行。

+1

1)這絕對不是標準。 [試試這個](http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2012/n3485.pdf)。 2)您沒有閱讀表格下方的註釋。官方至少有32位。 – chris

+0

@CaptainObvlious我試過了,但它也不起作用。 – user1810087

回答

2

因爲在您的編譯器中,您重載的所有類型tt都與long相同。在其他編譯器上,它們中的一個或多個可能是。最可能的是,int32_tint的別名,int64_tlong long的別名。

即使,例如,intlong是相同大小,它們不是相同型,因此對一個基準不能被轉換爲其他的引用。事實上,你已經引用了標準中表示它們是不同類型的部分。

+0

這表明long long是int64_t,至少在gcc上:http://ideone.com/clone/GmP0I0 –

+0

@ArneMertz:在網站運行的特定平臺上([32位Linux](http:// ideone。 COM/2bH16Z))。在我的電腦(64位Linux)上,它很「長」。 –

+0

是的,抱歉的不準確。 –

0

C++標準(N3225草案)說:

有五種標準符號整型:「符號字符」,「短整型」,「詮釋」,「長整型」和「很長很長INT」。在這個列表中,每種類型至少提供與列表中前面那些相同的存儲空間。

在MSVC12上,我在stdint.h中得到了typedef unsigned int uint32_t;

Eventhough unsigned long也是32位,它仍然是一個不同的類型。

因此,您的函數都沒有被重載以將(無符號)長引用作爲參數。

-edit- 如果您更改函數以按值取其參數,則由於對tt()的模糊調用,最終會出現錯誤。