2014-04-15 28 views
-1
template <typename _CountofType, size_t _SizeOfArray> 
char(*__countof_helper1(_CountofType(&_Array)[_SizeOfArray]))[_SizeOfArray]; 

#define _myCountOf(_Array) (sizeof(*__countof_helper1(_Array)) + 0) 

我想了解_countof宏,但無法理解它如何能夠計算出數組的大小。請有人解釋一下上面的代碼瞭解_countof宏

+0

以上重複對此宏有具體說明,也鏈接到更一般的解釋。 –

+0

另請閱讀:[有關在標識符中使用下劃線的規則/](http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-ac -identifier/228797#228797) –

回答

4

這是一個過於複雜的聲明。在現代C++中,你可以做這樣的:

template<typename T, size_t SizeOfArray> 
constexpr size_t countof(T (&array)[SizeOfArray]) { return SizeOfArray; } 

該解決方案的核心是T (&array)[SizeOfArray]:這是你需要傳遞一個數組引用的語法。編譯器推斷出TSizeOfArray,所以它會爲你拋出的任何數組都有有效的值。

在您的幫助程序中,程序員可能無法訪問constexpr,但仍想確保在編譯時評估表達式,而不是在運行時評估表達式。這很令人困惑,因爲C++函數聲明語法令人困惑:它聲明瞭一個函數,它接受任何類型和長度的數組並返回相同長度的字符數組。然後它使用sizeof來查找字符數組的長度並返回它。

+0

這裏也覆蓋了很好:https://stackoverflow.com/questions/437150/can-someone-explain-this-template-code-that-gives-me-the-size-of-數組 – Brian