c++ - 跟踪模板类的内存消耗

标签 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(T));
    }
}

这很好用。最近有人要求我支持 T == std::string。 当前的实现不起作用,因为 sizeof(std::string) 没有反射(reflect) std::string 的内存消耗(我需要调用 capacity()std::string 上)。根据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(); 
}

关于c++ - 跟踪模板类的内存消耗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43607574/

相关文章:

c++ - 在 Qt 中使用完成信号退出线程并进行 clean_up 的正确方法

c++ - 在 C++11 中同步整个类

C++ shared_ptr use_count for nullptr

c++ - 可变参数类型的部分模板特化和扩展到外部类型的可变参数包导致歧义

所有子类的c++模板特化

c++ - 指针和 C 风格数组变量的专用模板

c++ - 在 C++ 中设置带有 vector 的网格?

.net - Hook 来自托管代码的 LoadLibrary 调用

c++ - usual name lookup 是什么意思?

c++ - 类和结构在填充和继承方面的区别