我可以使用折叠表达式实现max

我可以使用折叠表达式实现max

本文介绍了我可以使用折叠表达式实现max(A,max(B,max(C,D)))吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

在尝试使用C ++ 17折叠表达式时,我尝试实现max sizeof ,其中结果是类型的 sizeof 的最大值.我有一个使用变量和lambda的丑陋折叠版本,但是我无法想到一种使用折叠表达式和 std :: max()来获得相同结果的方法.

While trying to play around with C++17 fold expressions, I tried to implement max sizeof where result is maximum of the sizeof of types.I have an ugly fold version that uses variable and a lambda, but I am unable to think of a way to use fold expressions and std::max() to get the same result.

这是我的折叠版本:

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个元素,应将其扩展为

I would like to write equivalent function using fold expressions and std::max().For example for 3 elements it should expand to

return std::max(sizeof (A), std::max(sizeof(B), sizeof (C)));

有可能这样做吗?

推荐答案

可能不是您想听到的,但没有.不可能用fold表达式(纯)做到这一点.他们的语法根本不允许这样做:

Probably not what you wanted to hear, but no. It isn't possible to do that (purely) with fold expressions. Their very grammar simply doesn't allow for it:

[expr.prim.fold]

fold-expression:
  ( cast-expression fold-operator ... )
  ( ... fold-operator cast-expression )
  ( cast-expression fold-operator ... fold-operator cast-expression )
fold-operator: one of
  +   -   *   /   %   ^   &   |   <<   >>
  +=  -=  *=  /=  %=  ^=  &=  |=  <<=  >>=  =
  ==  !=  <   >   <=  >=  &&  ||  ,    .*   ->*

仅是因为函数调用表达式不是纯粹的语法意义上的二进制运算符.

Simply because a function call expression is not a binary operator in the pure grammar sense.

这篇关于我可以使用折叠表达式实现max(A,max(B,max(C,D)))吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 08:38