Home > Mobile >  How to pass values directly to std::span?
How to pass values directly to std::span?

Time:12-31

I have a function that receives a span.

void p(std::span<int> s) {
    for(auto x : s) {
        std::cout << x << ' ';
    }

How can I pass values directly into the function? For instance.

p({1,2,3})

Any workaround?

CodePudding user response:

You can construct an std::array:

p(std::array{1,2,3});

This also requires you to use std::span<const int> instead of std::span<int>, since the latter expects a modifiable range (which doesn't seem to be your intent), and rejects rvalues.

CodePudding user response:

the closest to passing {1, 2, 3} would be to pass an std::initializer_list:

auto list = { 1, 2, 3 };
p(list);

or inlined:

p( std::initializer_list{ 1, 2, 3 } );

But however you take the span, p needs to accept an std::span<const int> to work, like HolyBlackCat mentioned..

CodePudding user response:

You can shorten what you need to write before {} by providing your own adapter. For example:

#include <iostream>
#include <span>

void p(std::span<const int> s) {
    for(auto x : s) {
        std::cout << x << ' ';
    }
}

template<typename T>
class spn
{
public:
    spn(std::initializer_list<T> list) : span_(list) {}
    operator std::span<const T>() {
        return span_;
    }
private:
    std::span<const T> span_;
};

int main()
{
    p(spn{1,2,3});
    return 0;
}
  • Related