I'm just into metaprogramming and was watching Cppcon channel on youtube, and saw this std::integral_constant
, but cannot find its use.
As far as i understood, it is a way to "pack" a value along with its type, it can be instantiated with
std::integral_constant<int, 42> i;
std::integral_constant<bool, true> b;
std::integral_constant<float, 3.14> f;
...
and each of those instances can be used just like the value they contains, i.e.: can be passed around, used in math operations, comparisons, etc.
But i cannot understand why should i use those structs instead of the actual contained values, nor if i can actually access the value type (i.e.: int
, bool
and float
) at runtime to do stuff with it.
Can someone present a simple example of practical use of this feature? An example that explain its usage difference from using the actual values?
std::integral_constant<int, 42>
is a type and42
is a value. It's many times easier to deal with a type then a value in you template code. Additionally it hasvalue_type
andtype
and con convert to a conpile time constant of the value when needed.