Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the rules on using `void` to specialize a template?

Tags:

c++

templates

Here's a stripped down illustration of what I just now wrote in the wild. I wasn't really expecting it to work, but it did.

#include <array>

template <typename T> using Foo = std::array<T,123>;

const int FOO_SIZE = std::tuple_size<Foo<void>>::value;

I wasn't sure using void to specialize Foo would compile, but it did, at least in this case.

I'm not confident that this solution is portable, or if it's just a fluke because the implementation of std::array happens to be compatible with the concept of an array-of-voids, which sounds like nonsense to me.

When can I, and when can I not, use void to specialize a template?

like image 590
spraff Avatar asked Nov 06 '22 22:11

spraff


1 Answers

I can't find a really convincing specific set of standard wording without reproducing half the standard (:D) but I believe that this is well-defined.

The array constructor requires that T be MoveConstructible or MoveAssignable, and you're not going to be able to instantiate a std::array<void, N>.

But that's fine, because std::tuple_size doesn't need to do that, and it isn't specified to need to do that, and neither thing makes any other specific requirements that would render your code problematic.

However, this does not seem like useful code, and there is no general rule for when void can be used as a template argument. You have to look at the requirements for the specific thing you're using, in the specific context in which you're using it.

like image 171
Lightness Races in Orbit Avatar answered Nov 15 '22 07:11

Lightness Races in Orbit