考虑以下功能:
template<typename... List>
inline unsigned int myFunction(const List&... list)
{
return /* SOMETHING */;
}
/* SOMETHING */
为了返回sizeof
所有参数的总和,最简单的方法是什么?
例如myFunction(int, char, double) = 4+1+8 = 13
考虑以下功能:
template<typename... List>
inline unsigned int myFunction(const List&... list)
{
return /* SOMETHING */;
}
/* SOMETHING */
为了返回sizeof
所有参数的总和,最简单的方法是什么?
例如myFunction(int, char, double) = 4+1+8 = 13
unsigned myFunction() {return 0;}
template <typename Head, typename... Tail>
unsigned myFunction(const Head & head, const Tail &... tail) {
return sizeof head + myFunction(tail...);
}
在 C++17 中,使用折叠表达式:
template<typename... List>
inline constexpr unsigned int myFunction(const List&... list)
{
return (0 + ... + sizeof(List));
}
根据此评论和对该问题的以下评论,您可以使用它(注意:完全未经测试)
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);
晚了两年,但保证由编译器计算一个替代解决方案(如果你不介意不同的语法):
template < typename ... Types >
struct SizeOf;
template < typename TFirst >
struct SizeOf < TFirst >
{
static constexpr auto Value = (sizeof(TFirst));
};
template < typename TFirst, typename ... TRemaining >
struct SizeOf < TFirst, TRemaining ... >
{
static constexpr auto Value = (sizeof(TFirst) + SizeOf<TRemaining...>::Value);
};
用作constexpr std::size_t size = SizeOf<int, char, double>::Value; // 4 + 1 + 8 = 13
这是一个模板方式:
#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;
}
我刚刚发现:
template<typename... List>
inline unsigned int myFunction(const List&... list)
{
return sizeof(std::make_tuple(list...));
}
但 :
1)我是否保证所有编译器的结果总是相同的?
2) make_tuple 会在编译时生成和开销吗?