Home > Enterprise >  How do I restrict fold expressions with C 20 requirements/concepts?
How do I restrict fold expressions with C 20 requirements/concepts?

Time:01-07

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); }
  •  Tags:  
  • Related