samedi 22 avril 2023

Is there a better practice than defining this constexpr struct in a header file?

I'm trying to design a program to play musical notes

To test each note, I created a series of constexpr structs to contain the frequency and period of each note in a header file and call them in the source files I want to test them.

MusicNotes.hpp

typedef struct Note_t{
    float frequency_hz {};
    uint32_t period_us {};
} Note_t;

class MusicalNotes{
public:
    MusicalNotes() {};
    void playNote(Note_t musicNote, uint32_t duration_ms);

    static constexpr Note_t C0 { 16.35, 61162};
    static constexpr Note_t CSh0_Db0 { 17.32, 57736};
...
    static constexpr Note_t ASh8_Bb8 { 7458.62, 134};
    static constexpr Note_t B8 { 7902.13, 126};
};

In another source file, I'll call something like:

void sendNote(void) {
    musicalNotes.playNote(musicalNotes.E4, 500);

I wish to have a the ability to call these Notes from a number of source files and I never plan to change these values which is why I preferred constexpr. However, I know there are pitfalls to defining all of this in a header file such as unnecessary copies of notes in each source file. I have run into issues regarding modifying an expression's lvalue and requiring an in-class initializer (I assume the class definition) when attempting to forward declare my current method.

Is it better practice to have these structs instead not be constexpr at all, forward declare them, and then define them in my MusicalNotes constructor, or will the multiple copies of the struct not represent a big problem?

Aucun commentaire:

Enregistrer un commentaire