【发布时间】:2018-01-13 15:46:07
【问题描述】:
下面是一个简化的模板类,它接受一个数组作为模板参数。但是,我还必须将数组的大小作为参数传递。我想自动推导出来,只写:
const char *TextArray[] = { "zero", "one", "two" };
Array<TextArray> a;
在实际实现中,类在编译时知道 TextArray 的大小,这是必需的(因为在编译时会检查它并与类中的其他项配对)。如果我指定了错误的大小,我会得到正确的编译器错误:
Array<100, TextArray> a;
类定义:
#include <iostream>
template <std::size_t N, const char * (&A)[N]>
class Array
{
public:
auto getCount()
{
return N;
}
auto getAt(std::size_t n)
{
return A[n];
}
};
const char *TextArray[] = { "zero", "one", "two" };
int main() {
Array<sizeof(TextArray)/sizeof(TextArray[0]), TextArray> a;
printf("a.getCount() is %zu\n", a.getCount());
printf("a.getAt(1) is %s\n", a.getAt(1));
}
输出:
a.getCount() 是 3
a.getAt(1) 是一
解决方案是使用宏,但我不想污染全局范围。一个微不足道的改进是更新类,以便我写:
Array<sizeof(TextArray), TextArray> a;
在 gcc、Visual Studio、clang 上使用 C++17
【问题讨论】:
标签: c++ arrays templates c++17