Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Something like std::integral_constant but with auto template argument in std C++20 library?

Starting from C++20 one can use auto template argument to implement integral constant:

Try it online!

template <auto Value>
struct integral_constant2
    : std::integral_constant<decltype(Value), Value> {};

which can be used instead of more verbose variant std::integral_constant that has two template arguments.

Sure its easier to write f(std::integral_constant2<123>{}); instead of more verbose f(std::integral_constant<int, 123>{});. More than that you may not know type in advance if you have complex compile-time expression.

My question is whether there exists in C++20 std library anything like integral_constant2 mentioned above, not to reinvent wheel? Or at least some std constexpr function std::make_integral_constant(123) that deduces std::integral_constant's template params?

like image 318
Arty Avatar asked Oct 16 '25 11:10

Arty


2 Answers

No, I am not aware of such replacement.

I believe it would be difficult to defend such proposal, given how easy it is to write your own. On the other hand the only reason might be that nobody proposed it yet.


Mainly as a curiosity, and expanding on a comment, you can take this one step further via:

#include <type_traits>

template <auto Value, template<typename A, A> typename C>
using automized = C< decltype(Value),Value>;

template <auto Value>
using integral_constant = automized<Value,std::integral_constant>;

int main() {
    struct S {};
    integral_constant<true> c0{};
    integral_constant<10> c1{};
    integral_constant<S{}> c2{};
}

automized would allow to forward an auto parameter to any template taking typename T, T value. However, it is rather limited because it only works for templates taking exactly those parameters, while getting the general case right is rather painful when type and non-type parameters can be mixed.

like image 149
463035818_is_not_a_number Avatar answered Oct 19 '25 00:10

463035818_is_not_a_number


You can see all new feature in C++20 here : https://en.cppreference.com/w/cpp/20

and I don't see anything related to integral_constant (and I don't see anything in the type_traits page either)

like image 31
Martin Morterol Avatar answered Oct 19 '25 02:10

Martin Morterol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!