views:

229

answers:

2

I saw that @GMan implemented a version of sizeof... for variadic templates which (as far as I can tell) is equivalent to the built in sizeof.... Doesn't this go against the second design principle: prefer libraries to language extensions?

+4  A: 

sizeof... is just sugar, I think.

sizeof is indeed core to the language as is ..., and although a countof function could exist we already have sizeof and ... reserved so we might as well make it convenient to get the count that way.

Contrarily, if sizeof and ... weren't reserved, the idea of adding such a thing would have probably failed because new keywords tend to be frowned upon. (The less the better.)

GMan
+7  A: 

From Variadic Templates (Revision 3) (N2080=06-0150), page 6:

Although not strictly necessary (we can implement count without this feature), checking the length of a parameter pack is a common operation that deserves a simple syntax. Moreover, this operation may become necessary for type-checking reasons when variadic templates are combined with concepts; see Section 3.3.

(Section 3.3 talks about concepts which is irrelevant now.)

KennyTM
`sizeof...` can also be applied equally well to template and function parameter packs. So `sizeof...(T)` and `sizeof...(t)` work equally well. A library based solution would work either with template or function parameter packs but not with both, i believe. Because one expansion produces a sequence of types, and the other expansion produces a sequence of expressions. Maybe writing it as `template<size_t...> struct count;` and then passing the pack as `count<sizeof(T)...>` could work. Since `sizeof` can handle both types and expressions that would seem to work, but it's clearly uglier :)
Johannes Schaub - litb