[英]Constexpr expand constructor parameter pack into member array (C++11)
I want to expand a pack of variadic parameters into a struct member in C++11. My approach is the following:我想将一组可变参数扩展为C++11中的一个结构成员。我的方法如下:
template <typename... Ts>
struct cxpr_struct
{
constexpr cxpr_struct(Ts... Args) : t_(Args...) {}
std::array<int, sizeof...(Ts)> t_;
};
int main()
{
cxpr_struct(10, 20, 30);
}
However, this yields the following error:但是,这会产生以下错误:
<source>:208:16: error: missing template arguments before '(' token
208 | cxpr_struct(10, 20, 30);
|
I know that my code has flaws.我知道我的代码有缺陷。 Eg the type of array is not determined from Ts (how can I do that?).
例如,数组的类型不是由 Ts 确定的(我该怎么做?)。 But how would I do this the proper way?
但是我将如何以正确的方式做到这一点? Is template argument deduction really not possible for the compiler?
编译器真的不可能进行模板参数推导吗?
EDIT: I have to use C++11编辑:我必须使用 C++11
due to c++11, you have to use something like that:由于 c++11,你必须使用类似的东西:
template <typename... Ts>
struct cxpr_struct
{
constexpr cxpr_struct(Ts... args) : t_{args...} {}
std::array<int, sizeof...(Ts)> t_;
};
template<typename... Ts>
cxpr_struct<Ts...> build(Ts...args){
return cxpr_struct<Ts...>(args...);
}
int main()
{
auto obj = build(10, 20, 30);
}
or better:或更好:
template <unsigned Size>
struct cxpr_struct
{
template<typename... Ts>
constexpr cxpr_struct(Ts... args) : t_{args...} {}
std::array<int, Size> t_;
};
template<typename... Ts>
cxpr_struct<sizeof...(Ts)> build(Ts...args){
return cxpr_struct<sizeof...(Ts)>(args...);
}
int main()
{
auto obj = build(10, 20, 30);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.