C++ 获取函数参数的字节数
c++ get number of bytes of the function arguments
如何获取函数参数的字节大小?
例子:
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) + ...);
}
如何获取函数参数的字节大小?
例子:
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) + ...);
}