问题
Considering the following function :
template<typename... List>
inline unsigned int myFunction(const List&... list)
{
return /* SOMETHING */;
}
What is the most simple thing to put instead of /* SOMETHING */
in order to return the sum of sizeof
all arguments ?
For example myFunction(int, char, double) = 4+1+8 = 13
回答1:
unsigned myFunction() {return 0;}
template <typename Head, typename... Tail>
unsigned myFunction(const Head & head, const Tail &... tail) {
return sizeof head + myFunction(tail...);
}
回答2:
In C++17, use a fold expression:
template<typename... List>
inline constexpr unsigned int myFunction(const List&... list)
{
return (0 + ... + sizeof(List));
}
回答3:
Based off of this comment and the following comments on the question, you could 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:
Two years late but an alternative solution guaranteed to be computed by the compiler (if you don't mind the 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
回答5:
Here's a template way:
#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;
}
回答6:
I've just found that :
template<typename... List>
inline unsigned int myFunction(const List&... list)
{
return sizeof(std::make_tuple(list...));
}
But :
1) Do I have the guarantee that the result will always be the same on all compilers ?
2) Do the make_tuple will make and overhead at compile-time ?
来源:https://stackoverflow.com/questions/12666761/sizeof-variadic-template-sum-of-sizeof-of-all-elements