[英]Capture size of array template parameter
使用數組非模板類型參數的時候,好像大小信息不單獨傳基本是無法恢復的。 例如,在模板中
template<const char CStr[]>
struct ToTemp {
...
}
任何對sizeof(CStr)
引用都將返回 8(或 4,取決於您的系統),因為它實際上是一個const char *
。 你可以聲明
template<const char CStr[5]>
struct ToTemp {
...
}
或者
template<int N, const char CStr[N]>
struct ToTemp {
...
}
但是第一個需要在編寫類時知道實際大小(不是很有用),而第二個需要單獨傳遞大小(這里沒有用 - 可能對強制執行大小限制有用)。 理想情況下,我會有類似的東西
template<const char CStr[int N]> //Let the compiler infer N based on the type
struct ToTemp {
...
}
或者
template<int N = -1, const char CStr[N]> //Declare N but let it be forced to a given value, so that I don't have to pass it in
struct ToTemp {
...
}
...但當然這些都不起作用。 最后,我希望能夠寫
const char foo[] = "abcd";
ToTemp<foo> bar;
並且讓bar
正確理解sizeof(foo)
是 5,而不必傳入單獨的sizeof(foo)
模板參數。
您可以使用全局字符串文字作為模板參數來匹配const char[]
並通過 constexpr 函數計算長度:
constexpr size_t GetSize(const char str[])
{
for (size_t i = 0; ; ++i)
{
if (str[i] == '\0')
{
return i;
}
}
}
template <const char str[]>
struct X
{
constexpr static auto Size = GetSize(str);
};
constexpr const char string[] = "42";
void foo()
{
X<string> x;
static_assert(X<string>::Size == 2, "");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.