Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is C++17 adding attributes to namespaces and enumerators?

As in the question states, I know there are going to be attributes for namespaces and enumerators in C++17. How will this influence our code? What are those attributes and what will they allow us to do? I could not find any good resource for understanding this new feature.

like image 388
DawidPi Avatar asked Sep 12 '15 17:09

DawidPi


People also ask

What is the purpose of namespace in C++?

Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries. All identifiers at namespace scope are visible to one another without qualification.

What are attributes in C++?

Attributes are modern ways in C++ to standardize things if their code runs on different compilers. Attributes are used to provide some extra information that is used to enforce conditions (constraints), optimization and do specific code generation if required.

What is the purpose of using namespace std?

In C++, a namespace is a collection of related names or identifiers (functions, class, variables) which helps to separate these identifiers from similar identifiers in other namespaces or the global namespace. The identifiers of the C++ standard library are defined in a namespace called std .

When was namespace added C++?

Namespaces were introduced to the C++ Standard in 1995 and usually they are defined like this: A namespace defines a new scope. They provide a way to avoid name collisions. Namespaces in C++ are most often used to avoid naming collisions.


1 Answers

Currently, If you were going to depreciate a particular enum value, you would need to rely on compiler extensions. For example, in clang, you would specify deprecated enum values the following way:

enum OperationMode {
  OM_Invalid,
  OM_Normal,
  OM_Terrified __attribute__((deprecated)),
  OM_AbortOnError __attribute__((deprecated)) = 4
};

Once enums and namespaces support attributes, there will be a standard cross-compiler way of implementing similar functionality:

enum OperationMode {
  OM_Invalid,
  OM_Normal,
  OM_Terrified [[deprecated("re-named to invalid")]],
  OM_AbortOnError  [[deprecated("exceptions are used instead")]] = 4
};

Other attributes may one day find relevance to namespaces and enumerated values, but as the proposal writer states:

This paper proposes resolving these issues by allowing attributes to be specified on enumerators and namespaces, and extends the [[deprecated]] attribute to apply to these entities, as was originally intended.

like image 65
Trevor Hickey Avatar answered Sep 28 '22 05:09

Trevor Hickey