cooky451
cooky451

Reputation: 3510

Protecting the rest of the world from system headers

Good day!

I am currently looking for "the" way to protect the rest of the program from system dependent header files. One often is unable to just put it in a detail namespace, due to dependencies of the system header itself. My consideration was now to use extern declared variables inside a detail namespace and give them a value inside a .cpp file which includes the system headers. This appeared to be the perfect solution, since the outer world doesn't even know most of the stuff, and all you need can be packed in a detail namespace. But there is one problem: You can not initialize enum constants with extern constants.

My question: Is there any way to use enum/struct types with extern variables? Or is there even a better way to protect the program from system headers?

VS11 says:

namespace detail
{
  extern const int value;
}

const auto val = detail::value; // ok

enum class my_enum
{
  value = detail::value, // "expression must have a constant value"
};

struct my_struct
{
  static const auto value = detail::value; // "constant value is not known"
};

Upvotes: 2

Views: 118

Answers (1)

I am not sure what you are trying to achieve, but if you intend on redefining new constants to have the exact same values as the old ones, the dependency on the system header is maintained.

The first way I can think of for removing the dependency would be to redefine the system header functionality in your own wrapper with your own constants for each feature (which can be enums if you want them to be, or plain constants defined in the header itself). Then in the implementation file, include the system header and remap the values from your constants to the values in the system header.

Upvotes: 1

Related Questions