当前位置 : 主页 > 网络编程 > 其它编程 >

具有隐式数组大小的模板参数-TemplateParameterwithimplicitarraysize

来源:互联网 收集:自由互联 发布时间:2023-07-02
Belowisasimplifiedtemplateclassthatacceptanarrayasatemplateparameter.HoweverIhaveto Below is a simplified template class that accept an array as a template parameter. However I have to pass also the size of the array as a parameter. I would
Belowisasimplifiedtemplateclassthatacceptanarrayasatemplateparameter.HoweverIhaveto

Below is a simplified template class that accept an array as a template parameter. However I have to pass also the size of the array as a parameter. I would like to deduce it automatically and to write just:

下面是一个简化的模板类,它接受一个数组作为模板参数。但是我必须将数组的大小作为参数传递。我想自动推断它并写出:

const char *TextArray[] = { "zero", "one", "two" };Array a;

In the actual implementation the class knows the size of TextArray at compile time, this is required (because at compiler time it is checked and paired with other items in the class). I get correctly a compiler error if I specify the wrong size:

在实际实现中,类在编译时知道TextArray的大小,这是必需的(因为在编译器时它被检查并与类中的其他项配对)。如果我指定了错误的大小,我会得到正确的编译错误:

Array a;

Class definiton:

#include template 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 a; printf("a.getCount() is %zu\n", a.getCount()); printf("a.getAt(1) is %s\n", a.getAt(1));}

Output:

a.getCount() is 3

a.getCount()是3

a.getAt(1) is one

a.getAt(1)是一个

A solution is to use a Macro, but I don't want to pollute the global scope. A trivial improvement is to update the class so that I write:

解决方案是使用宏,但我不想污染全局范围。一个微不足道的改进是更新类,以便我写:

Array a;

Using C++17 on gcc, Visual Studio, clang

在gcc,Visual Studio,clang上使用C ++ 17

1 个解决方案

#1

3

You can use auto in template parameter since C++17, e.g.

您可以在C ++ 17中使用auto in template参数,例如

template class Array{public: auto getCount() { return std::size(A); // also C++17 feature, #include } auto getAt(std::size_t n) { return A[n]; }};

BTW, you'd better explicitly cast a.getCount() to unsigned to match the %u specifier.

顺便说一下,你最好显式地将a.getCount()转换为unsigned以匹配%u说明符。

网友评论