簡體   English   中英

在C ++中使編譯時常數取決於類型大小的最佳方法是什么?

[英]What is the best way in C++ to have a compile-time constant depend on a type's size?

我在想其中之一:

#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;

另外,如何使用第二種方法拋出編譯時錯誤?

使用類模板的解決方案是一種很好的慣用方法(第一種選擇也不起作用,因此這兩位候選人之間沒有競爭)。

要導致編譯時錯誤,只需不為所有大小定義模板:

template <int S> class Foo;

然后,編譯器將抱怨未為有問題的sizeof(size_t)定義模板。

這也有助於將名稱從Foo更改為Environment_Where_sizeof_int_is東西-在實踐中,您會立即得到更多可以理解的編譯器錯誤。

使用g++您還可以使用以下預定義的宏:

__SIZEOF_SIZE_T__
__SIZEOF_INT__
__SIZEOF_LONG__

(對於其他類型,依此類推,請參閱文檔以獲取完整列表)。

例如:

#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

對定義的結構的第一個和第二個成員使用類型,並獲取第二個成員的偏移量以獲取第一個成員的大小(這假設第一和第二個成員之間沒有填充,保證第一個成員具有相同的地址作為結構)。

#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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM