获取 std::函数的可变参数模板参数类型的自定义大小

Get custom sizeof of std::function's variadic template argument types

本文关键字:参数 类型 自定义 变参 std 函数 获取      更新时间:2023-10-16

我有一个可变模板函数,它接受具有可变类型的std::函数。除了我想把doublefloat类型视为特殊类型,其中sizeof(double) == 100sizeof(float) == 50之外,我想找到std::function所具有的那些类型的总sizeof

这是伪代码(不编译)

#include <iostream>
#include <functional>
// terminating case for T=double
template<>
size_t getSize<double>()
{
    return 100;
}
// terminating case for T=float
template<>
size_t getSize<float>()
{
    return 50;
}
// terminating case for T being anything else
template<class T>
size_t getSize<T>()
{
    return sizeof(T);
}
// recursive case
template<class T, class ...S>
size_t getSize<T, ...S>()
{
    return getSize<T>() + getSize<S>();
}
template <class ...T>
void print_function_arg_custom_size(std::function<void(T...)> f)
{
    size_t totalSize = 0;
    // get size recursively
    totalSize = getSize<T>(); 
    std::cout << "totalSize: " << totalSize << std::endl;
}
void foo(uint8_t a, uint16_t b, uint32_t c, double d)
{
    // noop
}
int main()
{
    std::function<void(uint8_t, uint16_t, uint32_t, double)> f = foo;
    print_function_arg_custom_size<uint8_t, uint16_t, uint32_t, double>(f);
    return 0;
}

我遇到的问题之一是getSize不喜欢我的模板专业化。

几个错误:

template<class T>
size_t getSize<T>()
{
    return sizeof(T);
}

您不需要提供"专业化列表",因为它不是专业化。此外,由于参数包可以为空,编译器无法在重载getSize<T>getSize<T, S...>之间进行选择。要修复它,请进行以下更改:

template <typename T>
size_t getSize()
{
    return sizeof(T); 
}
// recursive case
template<class T, class U, class ...S>
size_t getSize()
{
    return getSize<T>() + getSize<U, S...>();
}

现场演示。