数组模板参数的捕获大小
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] == ' ')
{
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, "");
}
相关文章:
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 如何使用Visual Studio 2017在C++中为参数化对象数组使用唯一指针
- 为 NewObjectA() 函数创建 jvalues 的参数数组时出错 - JNI Invocation API
- 估计函数参数数组的维度
- 温度参数数组的内存泄漏
- 如何将值附加到命令行参数数组?
- libpqxx:如何绑定参数数组
- 如何在德尔福中C++参数数组指针算术
- C++函数参数或参数数组
- 将 std::function 代理为需要参数数组的 C 函数
- 分析字符串参数数组
- Pro*C传递参数数组
- OpenCV错误:cvGetSize中的错误参数(数组应该是CvMat或IplImage)
- c++无限参数数组
- 查找命令行参数数组中的元素数
- 如何将目录中所有具有完整路径的文件传递到execv中的参数数组
- ODBC:参数数组-忽略参数
- 使用lambda参数数组