C++ 跟踪模板类的内存消耗

C++ 跟踪模板类的内存消耗,c++,c++11,template-specialization,C++,C++11,Template Specialization,我有一个类,我想估算它消耗了多少内存: 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(

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

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));
    }
}
模板
类MyTemplateClass
{
大小\u t估计内存消耗()常量
{
//内存消耗是第一个模板参数大小的函数
返回f(sizeof(T));
}
}
这个很好用。最近我被要求支持
T==std::string
。 当前的实现不起作用,因为
sizeof(std::string)
没有反映
std::string
的内存消耗(我需要调用
std::string
上的
capacity()
)。根据,我不能为成员函数提供部分专门化(对于
T==std::string
,以及任何
U


有没有其他方法可以实现这一点?

您可以将内存消耗作为模板参数本身的函数

template <typename T, typename U>
class MyTemplateClass
{
    size_t EstimateMemoryConsumption() const
    {
        return estimate<T>(my_data_member);
    }
};
模板
类MyTemplateClass
{
大小\u t估计内存消耗()常量
{
回报估算(我的会员数据);
}
};

模板
大小估计(const t&)noexcept{return sizeof(t);}
模板
大小估计(常数标准::字符串和x)无例外
{ 
返回x.容量();
}

利用特质实现专业化:

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...
    }
};
模板
类MyTemplateClassTraits
{
公众:
静态大小\u t估计内存消耗(t和成员)
{
返回0;//实现。。。
}
};
模板
类MyTemplateClassTraits
{
公众:
静态大小\u t估计内存消耗(标准::字符串和成员)
{
返回0;//实现。。。
}
};
在不更改当前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);
    }

    //...
}
模板
类MyTemplateClass
{
//...
大小\u t估计内存消耗()常量
{
//内存消耗是第一个模板参数大小的函数
返回MyTemplateClassTraits::EstimateMemoryConsumption(t_数据_成员);
}
//...
}

用一个模板参数重构一个基类,然后从这个类派生。你不能一般地这样做,那么
std::vector
呢?对于您将找到的每个解决方案,您总是可以将其包装到另一个容器类中,从而破坏您的解决方案。您的问题不清楚是否存在单个T数据成员、T容器或其他任何内容。你能补充更多关于f是什么以及在数据中使用类型T的细节吗?这个答案很好,假设只有一个类型T的成员,但我不确定情况是否如此。
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);
    }

    //...
}