C++17 fold expression syntax?

只谈情不闲聊 提交于 2020-01-21 04:38:06

问题


I am trying to use compact fold expression without success.

For instance here is a working C++17 code

template <bool... B>
struct Fold_And : std::integral_constant<bool, (B && ...)>
{
};

template <bool... B>
constexpr auto Fold_And_v = Fold_And<B...>::value;


template <typename V, typename... Vs>
std::enable_if_t<
    Fold_And_v<std::is_floating_point_v<V>,
               std::is_floating_point_v<Vs>...> >
foo(const V& v, const Vs&...)
{
}

I want to translate it into a more compact form (not using the intermediate Fold_And)

template <typename V, typename... Vs>
std::enable_if_t<std::is_floating_point_v<V> && ... &&
                 std::is_floating_point_v<Vs> >
foo_compact(const V& v, const Vs&...)
{
}

However, this is apparently illegal C++ as both g++ and clang++ compilers fail to compile it.

My question:

  • is it only a syntax problem in foo_compact()? (what is the right one?)

Or

  • fold expression can not be used directy with complex subexpressions and we can not do better than using the 2 steps approach (foo() code using the Fold_And struct)?

回答1:


You almost got it! Fold expressions have to be surrounded by parentheses:

template <typename V, typename... Vs>
std::enable_if_t<(std::is_floating_point_v<V> && ... &&
                 std::is_floating_point_v<Vs>)>
foo_compact(const V& v, const Vs&...)
{
}

Notice the parentheses after < and before the last >.




回答2:


Fold expression requires parenthesis, so:

(std::is_floating_point_v<V> && ... && std::is_floating_point_v<Vs>)


来源:https://stackoverflow.com/questions/46958922/c17-fold-expression-syntax

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!