How do you restrict the allowed types in variadic templates and fold expression using C 20 concepts?
For example, supposed 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);
}
CodePudding user response:
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
CodePudding user response:
You can use type-constraint auto syntax:
int sum(std::integral auto... args) { return (... args); }
