Search code examples
c++templatesvariadic-templates

c++ get number of bytes of the function arguments


How do I get the size in bytes of function parameters? Example: void DummyFun(int64_t a, int32_t b, char c); The size in bytes is going to be 13.

I'm trying to solve this by using templates, but I'm not very good at it.

This is the contextualized code and what I tried so far:

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);  
    }
};


Solution

  • In C++17 you can use a fold expression:

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

    Demo