Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to express concepts over variadic template?

I'd like to define a concept which just tuples with values of a specific type can satisfy.

Let's say for simplicity I just want to accept tuples just holding elements of a numeric type. How would I do this?

e.g.

std::tuple<int16_t, int32_t> // satisfies concept
std::tuple<std::string, double> // doesn't satisfy concept

The problem is I'd have to formulate something like "for_each_type". Also recursive concepts are not allowed.

like image 367
user3520616 Avatar asked Dec 03 '22 17:12

user3520616


2 Answers

Simply enough:

namespace impl {
    template <class T>
    struct is_tuple_of_integrals
    : std::false_type { };
    
    template <std::integral... Ts>
    struct is_tuple_of_integrals<std::tuple<Ts...>>
    : std::true_type { };
}

template <class T>
concept tuple_of_integrals = impl::is_tuple_of_integrals<T>::value;

I do wonder whether the intermediate trait can be omitted, but absent concept specializations I don't believe so.

like image 134
Quentin Avatar answered Dec 11 '22 10:12

Quentin


My solution:

template<typename ... Args>
concept numeric_tuples = (std::is_integral_v<Args> && ...);

template<typename ... Args>
void foo(std::tuple<Args...> t) requires numeric_tuples<Args...> {

}

I used fold expression for the concept.

like image 40
stilgar Avatar answered Dec 11 '22 09:12

stilgar