简体   繁体   English

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

[英]Template Parameter with implicit array size

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<TextArray> 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). 在实际实现中,类在编译时知道TextArray的大小,这是必需的(因为在编译器时它会被检查并与类中的其他项配对)。 I get correctly a compiler error if I specify the wrong size: 如果我指定了错误的大小,我会得到正确的编译错误:

Array<100, TextArray> a;

Class definiton: 课程定义:

#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));
}

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<sizeof(TextArray), TextArray> a;

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

You can use auto in template parameter since C++17, eg 您可以 C ++ 17中使用auto in template参数 ,例如

template <auto &A>
class Array
{
public:
    auto getCount()
    {
        return std::size(A); // also C++17 feature, #include <iterator>
    }
    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说明符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM