数组模板参数的捕获大小

Capture size of array template parameter

本文关键字:参数 数组      更新时间:2023-10-16

当使用数组非模板类型参数时,似乎如果不单独传递大小信息,基本上无法恢复。例如,在模板中

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] == '')
{
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, "");
}