What would be the "correct" way to cast to dsp::AudioBlock<const float>*

casting dsp::AudioBlock<float> to dsp::AudioBlock<const float> is no problem.

but dsp::AudioBlock<float>* to dsp::AudioBlock<const float>* does not work (Incl. static and const-cast)

Currently I use reinterpret_cast<dsp::AudioBlock<const float>*> which is working, but it feels a bit like cheating. Is there are “correct” way to do this?

Disclaimer: This thread is not about why I use a pointer to an AudioBlock, which is already an lightweight object (I use a pointer because its an optional parameter) You might than add why I don’t use std::optional, but this is simply not the topic :wink:

It’s not the same type so no.
you can copy it beforehand and then pass the right pointer type but make sure the lifetime of the newly created AudioBlock is correct

It works for dsp::AudioBlock<float> to dsp::AudioBlock<const float> because there is a copy involved


I think there is no correct way to do this on a pointer cast level, except for reinterpret_cast which might be a last resort. But I wonder if it’s an option for you to simply dereference it in the context where you need the block of const samples, like

void foo (juce::dsp::AudioBlock<float>* optionalBlock)
    if (optionalBlock != nullptr)
        juce::dsp::AudioBlock<const float> constBlock = *optionalBlock;
        somethingThatNeedsTheConstBlock (constBlock);

Thanks for your helpful comments!

1 Like