This question already has answers here:
sizeof variadic template (sum of sizeof of all elements)

(6个答案)


19天前关闭。




如何获得函数参数的大小(以字节为单位)?
例:void DummyFun(int64_t a, int32_t b, char c);以字节为单位的大小将为13。
我正在尝试通过使用模板来解决此问题,但是我不是很擅长。
这是上下文化的代码,到目前为止,我一直在尝试:
template<typename T>
constexpr size_t getSize()
{
    return sizeof(T);
}

template<typename First, typename ... Others>
constexpr size_t getSize()
{
    return getSize<Others...>() + sizeof(First);
}

class NamelessClass
{
private:
    typedef void (*DefaultCtor)(void*);

    void HookClassCtor(DefaultCtor pCtorFun, size_t szParamSize);

public:
    template<typename T, typename ... Types>
    inline void HookClassCtor(T(*pCtorFun)(Types ...))
    {
        // I need the size in bytes not the count
        // HookClassCtor(reinterpret_cast<DefaultCtor>(pCtorFun), sizeof...(Types));

        size_t n = getSize<Types ...>();
        HookClassCtor(reinterpret_cast<DefaultCtor>(pCtorFun), n);
    }
};

最佳答案

在C++ 17中,您可以使用fold expression:

template<typename... Others>
constexpr size_t getSize() {
    return (sizeof(Others) + ...);
}
Demo

关于c++ - c++获取函数参数的字节数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/64657337/

10-11 22:10
查看更多