2
\$\begingroup\$

The goal of this code is to allow temporary RHS variables to be used in a span, specifically as an argument to a function, to be deleted later after the function completes, allowing the passing of temporaries to such span accepting functions.

How would I improve this code? Can I make it smaller and more readable? Is the temp_span api fine as it is to telegraph "Only put temporaries here" or is there something else I should be doing?

#include <gsl/span>
namespace gsl{


    template<typename T>
    class TempSpan{
    public:
        T value;
        explicit TempSpan(T&& t) : value(t){};
        operator gsl::span<typename T::value_type>() {
            return value;
        }
    private:
    };

    template<typename T>
    TempSpan<std::vector<T>> temp_span(std::initializer_list<T>&& t){
        return TempSpan(std::vector<T>(t));
    }
    template<typename T>
    TempSpan<T> temp_span(T&& t){
        return TempSpan(std::move(t));
    }

}

#include <iostream>

void foo(gsl::span<int> values){
    for(const auto& value: values){
        std::cout << value << "\n";
    }
}

int main(){
    foo(gsl::temp_span(std::vector<int>{1,2,3}));
    // 1
    // 2
    // 3
    foo(gsl::temp_span({4,5,6}));
    // 4
    // 5
    // 6
    return 0;
}
\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.