How do you restrict the allowed types in variadic templates and fold expression using C++20 concepts?
For example suppose I'd like to restrict the following fold expression to only support integral types, how would I do that?
#include <string>
#include <iostream>
#include <concepts>
using namespace std;
template<typename... Args> // requires (is_integral<Args>::value )
int sum(Args... args) { return (... + args); }
int main()
{
cout << sum(1,2,3);
}
The minimal change to make it work is:
requires (std::is_integral<Args>::value && ...)
I'd also suggest using the less verbose is_integral_v<...>
instead of is_integral<...>::value
.
Or, even better, a concept:
template <std::integral ...Args> // no requires needed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With