简体   繁体   中英

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:

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?). 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

due to c++11, you have to use something like that:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM