那么从理论上说,如果所有可能的(无符号)候选人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