2

我有一个存储std::array.

数组的大小是在编译时评估的,这是因为应用程序在嵌入式设备上运行,所以没有动态分配 :(。代码看起来像这样:

template<uint8_t size>
class A
{
    //some constructor
    A(...);
    std::array<int, size> what;
}
//Wanted use cases
A instance1({1,2,3});
//Unwanted use case
A<3> instance2({1,2,3});

我不知道如何构造我想要的构造函数。一个星期以来,我已经尝试了几十种设计,但没有一个能得到我想要的。以下是我尝试过的事物的名称:

  1. 模板扣除指南 - 也是模板版本,我不确定它们是否合法......
  2. std::initializer_list- 列表的大小不能放在模板参数中。至少不是在非 constexpr 上下文中。
  3. std::array
  4. 普通的旧数组
  5. using关键字 - 也是模板化的。

铊;博士:

如何从构造函数的签名中的给定数组中推导出表示数组类型大小的模板参数值?

4

2 回答 2

4

一个使用演绎指南的小例子:

template<uint8_t size>
class A
{
public:
    template <typename... Args>
    constexpr A(Args&&... args)
    : what { std::forward<decltype(args)>(args)... }
    {}
    constexpr size_t getSize() const { return what.size(); }
private:
    std::array<int, size> what;
};

//deduction guide
template <typename... Args> A(Args... args) -> A<sizeof...(args)>;

int main()
{
    //Wanted use cases
    A instance1 (1,2,3);
    static_assert (instance1.getSize() == 3);
    
    //or
    //A instance1 {1,2,3};
    return 0;
}
于 2020-07-29T14:03:11.473 回答
2
#include <array>

template<class... U>
class A
{
    std::array<int,sizeof...(U)> what;
public:
    constexpr A(U&&... u) : what{std::forward<U>(u)...} { }
    constexpr std::size_t size() const { 
        return what.size();
    }
};

int main() {
    A a(1,2,3,4,5,6);
    static_assert(a.size() == 6);

    A b(1);
    static_assert(b.size() == 1);
    
    return 0;
}
于 2020-07-29T14:02:11.933 回答