处理STL容器时的C ++类特化

时间:2011-09-17 22:43:54

标签: c++ templates stl vector specialization

我想要一个函数来返回对象的基本类型的字节大小。我还希望它返回STL容器的总大小(以字节为单位)。 (我知道这不一定是内存中对象的大小,这没关系。)

为此,我使用memorysize函数编写了一个bytes命名空间,以便memorysize::bytes(double x) = 8(在大多数编译器上)。

我专门用它来正确处理std::vector<double>类型,但我不想为表单std::vector<ANYTHING>的每个类编写不同的函数,所以如何正确地将模板更改为处理这种情况?

这是工作代码:

#include <iostream>
#include <vector>

// return the size of bytes of an object (sort of...)
namespace memorysize
{

  /// general object
  template <class T>
  size_t bytes(const T & object)
  {
    return sizeof(T);
  }

  /// specialization for a vector of doubles
  template <>
  size_t bytes<std::vector<double> >(const std::vector<double> & object)
  {
    return sizeof(std::vector<double>) + object.capacity() * bytes(object[0]);
  }

  /// specialization for a vector of anything???

}


int main(int argc, char ** argv)
{

  // make sure it works for general objects
  double x = 1.;
  std::cout << "double x\n";
  std::cout << "bytes(x) = " << memorysize::bytes(x) << "\n\n";

  int y = 1;
  std::cout << "int y\n";
  std::cout << "bytes(y) = " << memorysize::bytes(y) << "\n\n";

  // make sure it works for vectors of doubles
  std::vector<double> doubleVec(10, 1.);
  std::cout << "std::vector<double> doubleVec(10, 1.)\n";
  std::cout << "bytes(doubleVec) = " << memorysize::bytes(doubleVec) << "\n\n";

  // would like a new definition to make this work as expected
  std::vector<int> intVec(10, 1);
  std::cout << "std::vector<int> intVec(10, 1)\n";
  std::cout << "bytes(intVec) = " << memorysize::bytes(intVec) << "\n\n";

  return 0;
}

如何更改模板规范以允许更一般的std::vector<ANYTHING>案例?

谢谢!

1 个答案:

答案 0 :(得分:4)

相应地修改了您的代码:

/// specialization for a vector of anything
template < typename Anything >
size_t bytes(const std::vector< Anything > & object)
{
  return sizeof(std::vector< Anything >) + object.capacity() * bytes( object[0] );
}

请注意,如果使用空bytes调用vector,则现在遇到问题。

编辑:抓一点。如果我正确记住你以前的问题,那么如果你得到一个字符串向量,那么你想考虑每个字符串所采用的大小。所以你应该做

/// specialization for a vector of anything
template < typename Anything >
size_t bytes(const std::vector< Anything > & object)
{
  size_t result = sizeof(std::vector< Anything >);

  foreach elem in object
       result += bytes( elem );

  result += ( object.capacity() - object.size() ) * sizeof( Anything ).

  return result;
}