可变参数模板参数大小(不计数)
Variadic template argument size (not count)
在C++11中,我可以通过以下方式获得参数的聚合大小:
template<typename First, typename... Rest>
size_t getSize( const First& first, const Rest& ...rest )
{
return getSize(first) + getSize( rest... );
}
template <typename T>
size_t getSize( const T& )
{
return sizeof(T);
}
std::cout << "Size of arguments is: " << getSize( short(0), double(0.0) ) << std::endl;
输出将为:"参数大小为:10"。老C++有什么类比吗?
附言也欢迎C++11的更好解决方案
对于 C++11,我会使用它,它由编译时计算。
#include <iostream>
template<typename First, typename... Rest>
struct total_size_of
{
static constexpr size_t value = total_size_of<First>::value + total_size_of<Rest...>::value;
};
template <typename T>
struct total_size_of<T>
{
static constexpr size_t value = sizeof(T);
};
int main() {
std::cout << "Size of arguments is: " << total_size_of<short, double>::value << std::endl;
return 0;
}
对于 Pre-C++11,我会使用这样的东西(由于缺乏可变参数模板(。
#include <iostream>
template <typename T>
struct custom_size_of
{
static const size_t value = sizeof(T);
};
template <>
struct custom_size_of<void>
{
static const size_t value = 0;
};
template <typename One, typename Two = void, typename Three = void, typename Four = void>
struct total_size_of
{
static const size_t value = custom_size_of<One>::value + custom_size_of<Two>::value + custom_size_of<Three>::value + custom_size_of<Four>::value;
};
int main()
{
std::cout << "Size of arguments is: " << total_size_of<short, double>::value << std::endl;
return 0;
}
虽然 C++11 版本仍然很容易调整为自动确定参数类型的函数,但使用预C++没有很好的解决方案。
C++11:
template <typename...Args>
size_t get_size_of(Args...args)
{
return total_size_of<Args...>::value;
}
C++11 之前:
template <typename One>
static size_t get_size_of(const One&)
{
return total_size_of<One>::value;
}
template <typename One, typename Two>
static size_t get_size_of(const One&, const Two&)
{
return total_size_of<One, Two>::value;
}
template <typename One, typename Two, typename Three>
static size_t get_size_of(const One&, const Two&, const Three&)
{
return total_size_of<One, Two, Three>::value;
}
template <typename One, typename Two, typename Three, typename Four>
static size_t get_size_of(const One&, const Two&, const Three&, const Four&)
{
return total_size_of<One, Two, Three, Four>::value;
}
相关文章:
- 在不传递参数数量且只有3个点的情况下,如何使用变差函数
- 如何使用可变参数模板强制转换每个变体类型
- 关于如何在具有单个参数的变体构造中选择替代方案?
- 调用参数排列不变函数 f(i++, i++)
- 参数归纳与标准::变体
- 模板化回调参数的逆变,如 C# 中的逆变
- 如何在没有参数包的情况下编写变差函数
- 通过具有嵌套类的工厂类获取多个变异类模板参数包
- 获取模板参数的成员变量值列表
- 保留短 lambda 用作函数的中间参数,使用 clang 格式保持不变
- 如何定义变体<x,y,z>提取模板参数的子类型
- 正确对齐内存模板,参数顺序不变
- 递归中不同参数类型的变元模板函数
- 通过函数指针传递给变差函数的参数会更改其值
- 提升预定义为带有参数的全局 lambda 的变体访问者
- 使用可变参数模板参数提升变体访问者
- boost ::变体 - 为什么模板参数比const字符串参数具有更高的优先级
- 将变参数包中的值加载到临时数组中
- 使用额外参数提升变体访客
- 正在将动态数组元素解析为参数?(变音符)