Injected Class Name in C : Purpose and History
C features an intriguing concept known as the injected class name. By injecting the class name into its own scope, the language ensures that name lookup within the class always finds the current class, even when other similarly named classes exist in the same enclosing scope.
This feature becomes crucial in scenarios such as the following:
void X() { } class X { public: static X create() { return X(); } };
Is the create() function constructing a temporary X object or invoking the function X? In the global scope, the function X would be called. Thus, the injected class name guarantees that within the X class body, the name X always refers to the class itself, preventing potential ambiguity.
The injected class name also proves beneficial in class templates, allowing the template class to be referenced without specifying arguments, simplifying the expression.
Despite being conceptually present in C 98, the term "injected class name" was introduced in C 03 (DR 147). Prior to C 98, the ARM language specification implied the concept but lacked specific terminology.
Advantages of Injected Class Name:
The above is the detailed content of What is the Purpose and History of Injected Class Names in C ?. For more information, please follow other related articles on the PHP Chinese website!