Search code examples
c++c++11constexprtemplate-argument-deduction

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. E.g. 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


Solution

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