C ++ - 最佳实践#define值只写一次?

时间:2016-02-16 17:07:31

标签: c++ macros preprocessor-directive

在我们的代码中,我们需要处理配置,为此,我们需要将配置名称作为std :: string传递给我们自己的框架。

示例代码:

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

这些字符串只能在一个地方写入,并且不会在其他任何地方重复使用..除了2或3种配置外。

我的队友希望将其作为#define使用,并将其作为最佳实践使用。像

#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)

我在想,它只会花点时间阅读代码并交叉引用这些#defines的意思。

对于#define(或静态const,无论如何)它们是否真的是最佳实践,即使在一个地方使用它也会使用它?

有这个的好处是什么?

2 个答案:

答案 0 :(得分:3)

我更喜欢

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);

答案 1 :(得分: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;
};