Amount of the list of arbitrary elements



  • I've got

    Write a function that calculates the amount of the case list arbitrary length with different types of items on the list.

    I don't know how to give an arbitrary number of elements, especially different types.



  • What's that?

    template <typename ...P> struct sum_type;
    

    template <typename T>
    struct sum_type<T>
    {
    using type = T;
    };

    template <typename T, typename ...P>
    struct sum_type<T, P...>
    {
    using type = decltype(T()+typename sum_type<P...>::type());
    };

    template <typename ...P>
    using sum_type_t = typename sum_type<P...>::type;

    template <typename T>
    inline T sum(T t) { return t; }

    template <typename T, typename ...P>
    inline sum_type_t<T, P... > sum(T t, P... p)
    {
    return t + sum(p...);
    }

    Checked Discovering Modern C++ Gottschling.

    It's just that anything can be transferred to the function by three points: sum(double a, ...)but to recognize the different types within the function without the templates, I don't see that possibility.

    Update Here's another solution:

    template <typename T>
    inline T sum(T t) { return t; }

    template <typename T, typename ...P>
    inline auto sum(T t, P... p)
    {
    return [](auto a, auto b) { return a + b; }(t,sum(p...));
    }

    int main()
    {
    std::cout << sum(2, 2.5, ' ', false) << std::endl;
    }




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2