Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast constexpr int[] to void*

Tags:

c++

I have a static array of integers that I never want to change. I have a C-style function that wants to have this array as a void-pointer parameter. I am trying out different combinations of const_cast and reinterpret_cast, but I'm coming to the point where I have no clue of what I'm exactly doing and it keeps giving me errors.

class Foo
{
    static constexpr int bar[3] = {1,2,3};

    void method()
    {
        cfunction(reinterpret_cast<void*>(const_cast<int*>(&bar)));
    }
};

invalid const_cast from type 'const int ()[3]' to type 'int'

I see that it fails because the types don't match. I also tried const_cast<int[]>(bar), but const_cast wants to have a pointer or reference type.

Where can I read up on this subject? It's hard for me to understand what is going on here.

like image 412
Marnix Avatar asked Mar 21 '26 21:03

Marnix


1 Answers

cfunction((void*)bar); 

P.S. I 've seen lots of programmers struggling to use all these casts when, in reality, they only need the simple C cast. If you insist on the C++ cast style, then

cfunction(reinterpret_cast<void*>(const_cast<int*>(bar)));

(Remove the & from bar).

like image 81
Michael Chourdakis Avatar answered Mar 24 '26 10:03

Michael Chourdakis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!