具有隐式数组大小的模板参数 [英] Template Parameter with implicit array size

查看:65
本文介绍了具有隐式数组大小的模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;

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

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:

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.getCount() is 3

a.getAt(1)是一个

a.getAt(1) is one

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

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;

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

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

推荐答案

您可以使用 <自C ++ 17起,在模板参数中使用code> auto ,例如

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

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,最好显式转换 a.getCount() unsigned 来匹配%u 说明符。

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

这篇关于具有隐式数组大小的模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆