Patrick Wright
Patrick Wright

Reputation: 1663

Use constexpr for optional configuration

Right now, I use something like the following to provide configuration to "sub-projects" within my code:

//_config.h
#ifndef _CONFIG_H
#define _CONFIG_H

#if defined(USE_CONFIG_H) && USE_CONFIG_H == 1
#include <config.h>
#endif

#ifndef CONFIG_OPTION_1
//Default value for CONFIG_OPTION_1 
#define CONFIG_OPTION_1 10
#endif

#ifndef CONFIG_OPTION_2
//Default value for CONFIG_OPTION_2
#define CONFIG_OPTION_2 20
#endif

#endif

That way I can include _config.h in my sub-project, use the configuration values, and "override" them if necessary be defining USE_CONFIG_H at compile time and placing config.h in the include path.

Now, I have been trying to convert over as much old C-style code as I can to take advantage of the safer alternatives in C++. Once of these is converting constants defined using macros into constexpr values. For example

constexpr unsigned int CONFIG_OPTION_1 = 10;

The problem I am having is, how do I replicate the same behavior I had with macros being able to conditionally override the default configuration values?

Upvotes: 1

Views: 277

Answers (1)

eerorika
eerorika

Reputation: 238321

Macros are the only way to make conditional compilation, so you cannot get rid of them entirely. But you can use the macro to initialise a variable:

constexpr unsigned int NON_MACRO_CONFIG_OPTION_1 = CONFIG_OPTION_1;

Thereby getting the benefits of types.

Upvotes: 1

Related Questions