Starting from C++20 one can use auto
template argument to implement integral constant:
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?
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.