gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:25:53 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com