Sizeof variadic template (the sum of the size of all elements)

Given the following function:

template<typename... List> inline unsigned int myFunction(const List&... list) { return /* SOMETHING */; } 

What is the simplest thing instead of /* SOMETHING */ to return the sum sizeof all arguments?

For example myFunction(int, char, double) = 4+1+8 = 13

+6
source share
6 answers
 unsigned myFunction() {return 0;} template <typename Head, typename... Tail> unsigned myFunction(const Head & head, const Tail &... tail) { return sizeof head + myFunction(tail...); } 
+13
source

In C ++ 17, use the fold statement:

 template<typename... List> inline constexpr unsigned int myFunction(const List&... list) { return (0 + ... + sizeof(List)); } 
+5
source

Based on this comment and the following comments on this, you can use this (note: completely untested)

 std::initializer_list<std::size_t> sizeList = {sizeof(List)...}; //sizeList should be std::initializer_list, according to the comments I linked to return std::accumulate(sizeList.begin(), sizeList.end(), 0); 
+4
source

Two years later, but an alternative solution that can be computed by the compiler (if you are not against different syntax):

 template < typename ... Types > struct SizeOf; template < typename TFirst > struct SizeOf < TFirst > { static const auto Value = (sizeof(TFirst)); }; template < typename TFirst, typename ... TRemaining > struct SizeOf < TFirst, TRemaining ... > { static const auto Value = (sizeof(TFirst) + SizeOf<TRemaining...>::Value); }; 

Used as const int size = SizeOf<int, char, double>::Value; // 4 + 1 + 8 = 13 const int size = SizeOf<int, char, double>::Value; // 4 + 1 + 8 = 13

+2
source

Here is the template:

 #include <iostream> template<typename T, typename ...Ts> class PPackSizeOf { public: static const unsigned int size = sizeof(T) + PPackSizeOf<Ts...>::size; }; template<typename T> class PPackSizeOf<T> { public: static const unsigned int size = sizeof(T); }; template<typename ...Ts> class FixedSizeBlock { private: char block[PPackSizeOf<Ts...>::size]; public: }; int main( ) { FixedSizeBlock<char,long> b; std::cout << sizeof(b) << std::endl; return 0; } 
0
source

I just found that:

 template<typename... List> inline unsigned int myFunction(const List&... list) { return sizeof(std::make_tuple(list...)); } 

But:

1) Do I have a guarantee that the result will always be the same for all compilers?

2) Does make_tuple and overhead at compile time?

-2
source

Source: https://habr.com/ru/post/926636/


All Articles