Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template argument deduction for constrained parameter (bitset size) fails

Is there a way to make the compiler deduce the parameter size_t L using a constrained by concepts template argument?

That's the best I got

template <typename T, size_t L>
concept def_bitset = std::is_same<T, std::bitset<L>>::value;

template<size_t L>
void stamp(def_bitset<L> auto const &b) {
    std::cout << b << std::endl;
}

This works if I call it passing the L as a template argument

stamp<4>(bitset<4>{0b0110});

I'd like to be able to call stamp without repeating the bitset size.

like image 868
Julio Rodrigues Avatar asked Oct 15 '20 11:10

Julio Rodrigues


Video Answer


1 Answers

Concepts exist to check constraints on template arguments. A concept is not a type, despite appearing in the same location as a type can when employing terse notation. It doesn't carry any type information that can be used for template argument deduction.

To illustrate it, let's rewrite your terse function template definition to its explicit form

template<size_t L, def_bitset<L> T>
void stamp(T const &b) {
    std::cout << b << std::endl;
}

This equivalent form should illustrate the problem. The concept can only check the constraint holds after T and L have been deduced. But while T is easy enough to deduce, this function template definition is not written in a way that allows deducing L from b. Therefore you encountered the need to specify L explicitly. The concept is of no help, because it's not part of the function argument, it's part of the template itself.

Now, it just so happens that the use case in the question doesn't really require a concept at all.

template<size_t L>
void stamp(std::bitset<L> const &b) {
    std::cout << b << std::endl;
}

This is a function template that expects specializations of std::bitset.

like image 161
StoryTeller - Unslander Monica Avatar answered Sep 22 '22 21:09

StoryTeller - Unslander Monica