那麼從理論上說,如果所有可能的(無符號)候選人size_t
上市不打擾你,你可以利用SFINAE的:
template <class T, class N = void, bool = sizeof(T) == sizeof(sizeof(T))>
struct TL {
typedef typename N::type type;
};
template <class T, class N>
struct TL<T, N, true> {
typedef T type;
};
typedef TL<unsigned short,TL<unsigned int, TL<unsigned long, TL<unsigned long long> > > >::type SizeT;
[live demo]
編輯:
針對不同編譯器的解決方法unsigned long
從unsigned long long
儘管他們假定sizeof(unsigned long) == sizeof(unsigned long long)
:
template <class U>
U *declptrval(U);
template <class U>
char is_exact(U *);
template <class U>
short is_exact(...);
template <class T, class N = void, bool = sizeof(is_exact<T>(declptrval(sizeof(T))))==sizeof(char)>
struct TL {
typedef typename N::type type;
};
template <class T, class N>
struct TL<T, N, true> {
typedef T type;
};
typedef TL<unsigned short,TL<unsigned int, TL<unsigned long, TL<unsigned long long> > > >::type SizeT;
[live demo]
你或許應該標記這個問題,C++ 03或C++ 98,但不是C++ 11,對不對? – Rakete1111
*爲什麼*你不想包含任何標準頭文件?它們通常不那麼大,並且不會顯着影響編譯時間。而且,如果定義了'size_t'的實際上沒有任何函數定義,那就意味着不會爲它們生成任何代碼。你能否通過定義你自己的類型來詳細說明你想解決的*實際問題? –
'cstddef'是一個很小的標題,就符號而言。命名空間污染真的太多了嗎? – StoryTeller