Home > front end >  Decay std::array to pointer
Decay std::array to pointer

Time:09-29

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?

CodePudding user response:

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.

  • Related