8

I would like to write a sum function with variable number of argument with the condition that it should ignore argument that are not std::is_arithmetic

I have figured out a recursive version that works

auto old_sum(){
    return 0;
}

template<typename T1, typename... T>
auto old_sum(T1 s, T... ts){
    if constexpr(std::is_arithmetic_v<T1>)
        return s + old_sum(ts...);
    else
        return old_sum(ts...);
}

I am wondering if I can use the if constexpr in the context of fold expression to make the following code only considers arithmetic types from the argument pack:

template<typename... T>
auto fold_sum(T... s){
    return (... + s);
}
4

2 回答 2

12

由于我们没有三元constexpr运算符,我们可以使用 lambda 代替。

#include <type_traits>

template<typename... T>
constexpr auto fold_sum(T... s){
    return (... + [](auto x)
    {
        if constexpr(std::is_arithmetic_v<T>) return x;
        else return 0;
    }(s));
}

用法:

int main()
{
    static_assert(fold_sum(0, nullptr, 5, nullptr, 11, nullptr) == 16);
}

godbolt.org 上的实时示例

于 2018-12-14T17:28:10.533 回答
3

你绝对想用if constexpr

我提出了一个不同的选择:std::get()std::pair模拟constexpr如下三元运算符(Vittorio Romeo 的改进;谢谢)

#include <utility>
#include <type_traits>

template<typename ... Ts>
constexpr auto fold_sum (Ts const & ... s)
 { return (... + std::get<std::is_arithmetic_v<Ts>>(std::pair{0, s})); }

int main ()
 {
   static_assert(fold_sum(0, nullptr, 5, nullptr, 11, nullptr) == 16);
 }
于 2018-12-14T18:21:38.900 回答