1

我在想其中之一:

#if sizeof(size_t) == 8
const size_t foo = 12345;
#elif sizeof(size_t) == 4
const size_t foo = 123;
#else
#error "Unsupported size_t size"
#endif

或者

template <int S> class Foo { static const size_t foo = 0; };
template <> class Foo<8> { static const size_t foo = 12345; };
template <> class Foo<4> { static const size_t foo = 123; };
const size_t foo = Foo<sizeof(size_t)>::foo;

另外,如何使用第二种方法引发编译时错误?

4

3 回答 3

4

使用类模板的解决方案是一种很好的惯用方式(第一个替代方案也行不通,因此这两个候选人之间没有竞争)。

要导致编译时错误,只需不要为所有大小定义模板:

template <int S> class Foo;

然后编译器会抱怨没有为sizeof(size_t).

将名称从更改Foo为类似的名称也会有所帮助Environment_Where_sizeof_int_is——在实践中,您会得到更容易理解的编译器错误。

于 2015-01-24T00:15:48.243 回答
1

With g++ you can also use the following predefined macros:

__SIZEOF_SIZE_T__
__SIZEOF_INT__
__SIZEOF_LONG__

(and so on for the other types, see the documentation for a complete list).

For example:

#if __SIZEOF_SIZE_T__ == 8
const size_t foo = 12345;
#elif __SIZEOF_SIZE_T__ == 4
const size_t foo = 123;
#else
#error "Unsupported size_t size"
#endif
于 2015-01-24T00:31:05.060 回答
0

使用已定义结构的第一个和第二个成员的类型并获取第二个成员的偏移量以获得第一个成员的大小(这假设第一个和第二个成员之间没有填充,第一个成员保证具有相同的地址作为结构)。

#define ofs(s,m)   (size_t)&(((s *)0)->m)

typedef struct S_{
size_t a;       /* type to get the size of */
size_t b;       /* make this same type as above */
}S;

int main()
{
size_t c;
    c = ofs(S,b);   /* get size of S.a */
    return(0);
}
于 2015-01-24T01:02:36.927 回答