How to use std::integral_constant for a struct? [duplicate]

  c++, c++11, c++17, c++20, typetraits

I am trying to use metaprogramming in my work. I have a struct and I want to use std::integral_constant to wrap it.

Here’s my code:

#include <type_traits>

struct Dims {
  unsigned lenX;
  unsigned lenY;
  unsigned lenZ;
};

int main() 
{
    typedef std::integral_constant<unsigned, 1> one_t; // This is ok
    constexpr Dims d{};  // This is ok
    typedef std::integral_constant<Dims, Dims{.lenX = 2, .lenY=3, .lenZ=4}> dim234_t; // This is not ok

    return 0;
}

I am getting an error:

n file included from <source>:1:
/opt/compiler-explorer/gcc-10.3.0/lib/gcc/x86_64-linux-gnu/10.3.0/../../../../include/c++/10.3.0/type_traits:56:30: error: a non-type template parameter cannot have type 'Dims' before C++20
  template<typename _Tp, _Tp __v>
                             ^
<source>:13:18: note: while substituting prior template arguments into non-type template parameter '__v' [with _Tp = Dims]
    typedef std::integral_constant<Dims, Dims{.lenX = 2, .lenY=3, .lenZ=4}> dim234_t;
                 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 error generated.
ASM generation compiler returned: 1
In file included from <source>:1:
/opt/compiler-explorer/gcc-10.3.0/lib/gcc/x86_64-linux-gnu/10.3.0/../../../../include/c++/10.3.0/type_traits:56:30: error: a non-type template parameter cannot have type 'Dims' before C++20
  template<typename _Tp, _Tp __v>
                             ^
<source>:13:18: note: while substituting prior template arguments into non-type template parameter '__v' [with _Tp = Dims]
    typedef std::integral_constant<Dims, Dims{.lenX = 2, .lenY=3, .lenZ=4}> dim234_t;
                 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 error generated.
Execution build compiler returned: 1

How do I make this work? Why does the unsigned work but the struct doesn’t? I did try to look for similar questions in stack overflow but didn’t find any.

Source: Windows Questions C++

LEAVE A COMMENT