sizeof可变参数模板(所有元素的sizeof之和)

时间:2012-10-01 02:05:19

标签: c++ c++11 tuples sizeof variadic-templates

考虑以下功能:

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

为了返回/* SOMETHING */所有参数的总和而放置sizeof最简单的事情是什么?

例如myFunction(int, char, double) = 4+1+8 = 13

6 个答案:

答案 0 :(得分:13)

unsigned myFunction() {return 0;}

template <typename Head, typename... Tail>
unsigned myFunction(const Head & head, const Tail &... tail) {
    return sizeof head + myFunction(tail...);
}

答案 1 :(得分:7)

在C ++ 17中,使用折叠表达式:

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

答案 2 :(得分:4)

基于this comment和以下关于该问题的评论,你可以使用它(注意:完全未经测试)

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);

答案 3 :(得分:2)

迟了两年但是保证由编译器计算的替代解决方案(如果你不介意不同的语法):

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);
};

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

答案 4 :(得分:0)

这是一种模板方式:

#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;
}

答案 5 :(得分:-2)

我刚刚发现:

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

但是:

1)我是否保证所有编译器的结果始终相同?

2)make_tuple会在编译时产生和开销吗?