【问题标题】:Template Parameter with implicit array size具有隐式数组大小的模板参数
【发布时间】: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


    【解决方案1】:

    你可以使用 auto in template parameter 从 C++17 开始,例如

    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];
        }
    };
    

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

    【讨论】:

    • 啊,我没有注意到这个新功能。现在我只需要等到 Visual Studio 实现它,但可以在 gcc/clang 上完美运行。顺便说一句,%zu 做到了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-20
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-01
    相关资源
    最近更新 更多