【发布时间】:2018-03-06 09:09:33
【问题描述】:
在尝试使用 C++17 折叠表达式时,我尝试实现 max sizeof,其中结果是 sizeof 类型的最大值。
我有一个使用变量和 lambda 的丑陋折叠版本,但我想不出一种方法来使用折叠表达式和 std::max() 来获得相同的结果。
这是我的折叠版本:
template<typename... T>
constexpr size_t max_sizeof(){
size_t max=0;
auto update_max = [&max](const size_t& size) {if (max<size) max=size; };
(update_max(sizeof (T)), ...);
return max;
}
static_assert(max_sizeof<int, char, double, short>() == 8);
static_assert(max_sizeof<char, float>() == sizeof(float));
static_assert(max_sizeof<int, char>() == 4);
我想使用折叠表达式和std::max() 编写等效函数。
例如对于 3 个元素,它应该扩展为
return std::max(sizeof (A), std::max(sizeof(B), sizeof (C)));
有可能吗?
【问题讨论】:
-
max(std::initializer_list<T>)存在。 -
是否有理由使用折叠,而不仅仅是
template<typename... T> constexpr size_t max_sizeof(){ return std::max({sizeof(T)...}); } -
@DaveS 为什么它不起作用? live on coliru
-
@schorsch312 : 那么它不可能是
constexpr。 -
template<class... Ts> constexpr std::size_t max_sizeof = sizeof(std::aligned_union_t<1, Ts...>);
标签: c++ templates variadic-templates c++17 fold-expression