【问题标题】:C++ class specialiation when dealing with STL containers处理 STL 容器时的 C++ 类特化
【发布时间】:2011-09-17 22:43:53
【问题描述】:

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

为此,我编写了一个带有bytes 函数的memorysize 命名空间,这样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&lt;ANYTHING&gt; 案例?

谢谢!

【问题讨论】:

    标签: c++ templates stl vector specialization


    【解决方案1】:

    相应地修改了您的代码:

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

    请注意,如果使用空的vector 调用bytes,现在会出现问题。

    编辑:从头开始。如果我没记错您之前的问题,那么如果您得到一个字符串向量,那么您需要考虑每个字符串所占用的大小。所以你应该这样做

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

    【讨论】:

    • 完美,谢谢!现在,我不处理字符串,所以我想我会跳过 foreach 步骤,只检查容量 = 0 时的情况。嗯... 6 分钟响应时间,我应该更频繁地在这里发布。 :)
    • capacity = 0 不会按照你的想法去做。最好检查vector.empty()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-10
    • 2011-06-22
    • 1970-01-01
    • 1970-01-01
    • 2011-02-07
    相关资源
    最近更新 更多