获取 std::函数的可变参数模板参数类型的自定义大小
Get custom sizeof of std::function's variadic template argument types
我有一个可变模板函数,它接受具有可变类型的std::函数。除了我想把double
和float
类型视为特殊类型,其中sizeof(double) == 100
和sizeof(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...>();
}
现场演示。
相关文章:
- 扩展C++生成的代码的模板参数类型名称
- 如何在 c++ 中定义接受不同参数类型的函数向量?
- 在 C++ 中运行时调用模板时,是否可以切换模板的参数类型?
- 将函数参数类型声明为 auto
- 将函数的参数 - 签名从使用 'std::function<T>' 转换为模板参数类型
- 在 C++17 中调用具有不同参数类型的构造函数
- 具有先前参数类型匹配的参数包
- 我想知道为什么"std::unique_ptr<int> foo(新 int)"是合法的,因为"std::<int>unique_ptr"要求输入参数类型应该是"int"?
- 将可变参数类型列表的扩展打包为复杂类型的初始值设定项列表 - 合法吗?
- MSVC 错误:4 个重载中的任何一个都无法转换所有参数类型
- 使用constexpr + auto作为返回和参数类型的奇怪类型推导
- 如何从第一个参数推断第二个参数类型?
- C++模板函数中,指定回调函子/lambda 的参数类型,同时仍允许内联?
- 如何用不同的参数类型和数字回调函数
- C++stoi:这两个重载都无法转换所有参数类型
- 为什么std::{container}::template不能推导其参数类型
- 为模板参数类型中的新对象分配内存
- 为指向成员模板参数的指针推导额外模板参数类型的紧凑方式
- 使用std::conditional中的模板来确定函数参数类型
- C++中的短参数类型