Best #define values ​​methods that are written only once?

in our code, we need to process the configurations, and for this we need to pass the configuration names as std :: string to our own infrastructure.

Code example:

framework.handle_config("enable-radio-link")
framework.handle_config("enable-tv-link")
framework.handle_config("enable-gateway-link")
so on to ...n

These lines will be recorded only in one place, and they will not be repeated anywhere else .. except for two or three configurations.

My team mate wanted to have it as #define and use it as best. as

#define ENABLE_RADIO_LINK "enable-radio-link"
#define ENABLE_TV_LINK "enable-tv-link"
framework.handle_config(ENABLE_RADIO_LINK)
framework.handle_config(ENABLE_TV_LINK)

I thought it would just take a little longer to read the code and cross-reference what these #defines mean.

This is really best practice: use #define (or static const any) to use them, although it is used in one place?

What is the advantage of this?

+4
2

const std::string ENABLE_RADIO_LINK = "enable-radio-link";

, , . , , , .

, , , . :

namespace FrameworkConsts {
    const std::string ENABLE_RADIO_LINK = "enable-radio-link";
    const std::string ENABLE_TV_LINK = "enable-tv-link";
    /*etc.*/
}

:

framework.handle_config(FrameworkConsts::ENABLE_RADIO_LINK);
+3

, " " enum class. , include . , .

enum class MyConfiguration {
    EnableRadioLink,
    EnableTVLink
};

void enableConfig(MyConfiguration config) {
    // Do something with config
}

int main() {
    //...
    enableConfig(MyConfiguration::EnableRadioLink);
    enableConfig(MyConfiguration::EnableTVLink);
    //...
    return 0;
};
+3

Source: https://habr.com/ru/post/1629026/


All Articles