我有一个存储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});我不知道如何构造我想要的构造函数。我已经试了一个星期了,现在已经有几十种设计了,但都没有得到我想要的。以下是我尝试过的东西的名字:
std::arrayusing关键字中没有模板化.。
Tl;Dr:
如何从构造函数的签名中从给定数组中推导出表示数组类型大小的模板参数值?
发布于 2020-07-29 14:03:11
一个使用演绎指南的小例子:
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-29 14:02:11
#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;
}https://stackoverflow.com/questions/63154987
复制相似问题