Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Decay std::array to pointer

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading