1

I have class like this:

struct S{
    void method1(int *a){
       // use a
    }

    void method2(int *a){
       // use a
    }
};

To avoid allocation, I am doing following:

std::array<int, 100> a;
S s;
s.method1(a.data());

However much nicer will be if I can able to do, without making all methods templates.

std::array<int, 100> a;
S s;
s.method1(a);

In C++20 I can use std::span, but currently I want to avoid it as well.

Any easy way to define some operator that will be able to convert / cast, but only inside the class?

3
  • 5
    One of the purposes of std::array is not to decay to a pointer. You may use int a[100] if you need the implicit array to pointer decay. Commented Sep 29, 2022 at 9:27
  • A side note: not sure it's a good idea to use std::array for a, as it will occupy ~400 bytes (assuming int is 4 bytes) on the stack which is quite a lot. Commented Sep 29, 2022 at 9:27
  • @paolo you are right. but I want something in between ;) I want to be able to return std::array from function and pass it, without specifying .data() every time. std::span is made exactly for this. Commented Sep 29, 2022 at 9:30

1 Answer 1

5

You can use non-member std::data and call it like s.method1(std::data(a));.

That works for raw arrays, std::array, std::span and others.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.