How to pass a temporary array?

前端 未结 2 1256
夕颜
夕颜 2020-12-07 01:38

How can I pass a temporary array? I want to do something like this:

#include 

int sum(int arr[]) {
    int answer = 0;
    for (const auto&a         


        
2条回答
  •  春和景丽
    2020-12-07 02:07

    I suggest making the sum function a template that accepts any range instead of limiting it to arrays. This way you could use the function with standard containers like std::vector, std::set or even user-defined containers too.

    My solution requires the boost.range library but who isn't using boost today? Ranges are even considered to be added to the standard library.

    #include 
    #include 
    #include 
    #include 
    #include 
    #include     
    
    template< typename Range >
    auto sum_impl( const Range& range ) -> typename boost::range_value< Range >::type
    {
        typename boost::range_value< Range >::type result{};
        for( const auto& elem : range )
            result += elem;
        return result;
    }
    
    template< typename Range >
    auto sum( const Range& range ) -> typename boost::range_value< Range >::type
    {
        return sum_impl( range );
    }
    
    template< typename Elem >
    Elem sum( const std::initializer_list< Elem >& range )
    {
        return sum_impl( range );
    }
    
    int main()
    {
        // Call the initializer_list overload
        std::cout << sum( { 1, 2, 3 } ) << "\n";
        std::cout << sum( { 1.0f, 2.1f, 3.2f } ) << "\n";
    
        // Call the generic range overload
        std::cout << sum( std::array{ 1, 2, 3 } ) << "\n";
        std::cout << sum( std::vector{ 1.0f, 2.1f, 3.2f } ) << "\n";
        std::cout << sum( std::vector{ "a", "b", "c" } ) << "\n";  
    }
    

    Some explanations:

    • I'm using auto as return type just to make the function declaration more readable. You could also write it like this:

      typename boost::range_value< Range >::type sum( const Range& range )

    • The boost::range_value template is used to deduce the type of the elements of the range. This way we can use sum() not only for ints, but anything that has an operator += defined! You can see in my example that we can even "add" (concatenate) strings together. :D

    • The overload taking a std::initializer_list parameter finally makes the easy syntax possible where we can call sum({ 1, 2, 3 }) as requested by the OP. This overload is required because the generic overload won't deduce the initializer_list argument type (see also initializer_list and template type deduction )

    Demo:

    http://coliru.stacked-crooked.com/a/80393e710fc355a6

提交回复
热议问题