跟踪模板的内存消耗 class

Tracking memory consumption of a template class

我有一个 class,我想估计它消耗了多少内存:

template <typename T, typename U>
class MyTemplateClass
{
    size_t EstimateMemoryConsumption() const
    {
        // the memory consumption is a function of the size of the first template argument
        return f(sizeof(T));
    }
}

这很好用。最近有人要求我支持 T == std::string。 当前的实现不起作用,因为 sizeof(std::string) 没有反映 std::string 的内存消耗(我需要在 std::string 上调用 capacity())。根据 this,我无法为成员函数(对于 T == std::string 和任何 U

提供偏特化

是否有其他方法可以实现此目的?

您可以使内存消耗成为模板参数本身的函数。

template <typename T, typename U>
class MyTemplateClass
{
    size_t EstimateMemoryConsumption() const
    {
        return estimate<T>(my_data_member);
    }
};

template <typename T>
size_t estimate(const T&) noexcept { return sizeof(T); }

template <>
size_t estimate<std::string>(const std::string& x) noexcept 
{ 
    return x.capacity(); 
}

利用特质实现专业化:

template <typename T>
class MyTemplateClassTraits
{
public:
    static size_t EstimateMemoryConsumption(T& member)
    {
        return 0; // implement...
    }
};

template <>
class MyTemplateClassTraits<std::string>
{
public:
    static size_t EstimateMemoryConsumption(std::string& member)
    {
        return 0;  // implement...
    }
};

不改变你当前的 API:

template <typename T, typename U>
class MyTemplateClass
{
    //...

    size_t EstimateMemoryConsumption() const
    {
        // the memory consumption is a function of the size of the first template argument
        return MyTemplateClassTraits<T>::EstimateMemoryConsumption(t_data_member);
    }

    //...
}