当使用数组非模板类型参数时,如果不单独传递的话,似乎基本上无法恢复大小信息。例如,在模板中
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, "");
}
关于c++ - 捕获数组模板参数的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57588506/