Replacing text macros
Материал из cppreference.com
< cpp | preprocessor
|
|
This page has been machine-translated from the English version of the wiki using Google Translate.
The translation may contain errors and awkward wording. Hover over text to see the original version. You can help to fix errors and improve the translation. For instructions click here. |
Препроцессор поддерживает замену текста макроса. Функция-как текст макроса замены Также поддерживается.
Original:
The preprocessor supports text macro replacement. Function-like text macro replacement is also supported.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Содержание |
[править] Синтаксис
#define identifier replacement-list
|
(1) | ||||||||
#define identifier( parameters ) replacement-list
|
(2) | ||||||||
#define identifier( parameters, ... ) replacement-list
|
(3) | ||||||||
#define identifier( ... ) replacement-list
|
(4) | ||||||||
#undef identifier
|
(5) | ||||||||
[править] Объяснение
[править] NJ директивы
#define директивы определяют identifier как макро, то есть указать компилятору, чтобы заменить все последовательные вхождения identifier с replacement-list, который опционально может быть дополнительно обработаны. Если идентификатор уже определен как любой тип макросов, программа плохо сформированных. Original:
The
#define directives define the identifier as macro, that is instruct the compiler to replace all successive occurrences of identifier with replacement-list, which can be optionally additionally processed. If the identifier is already defined as any type of macro, the program is ill-formed. The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[править] Объекта, как макросы
Объект типа макросов заменить каждое вхождение определенных identifier с replacement-list. Версия (1),
#define директива ведет себя именно так.Original:
Object-like macros replace every occurrence of defined identifier with replacement-list. Version (1) of the
#define directive behaves exactly like that.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[править] Функция подобных макросов
Функция подобных макросов заменить каждое вхождение определенных identifier с replacement-list, дополнительно принимает ряд аргументов, которые затем заменить соответствующие вхождения любого из parameters в replacement-list. Число аргументов должно быть таким же, как количество аргументов в определении макроса (parameters) или программа плохо сформированные. Если идентификатор не находится в функциональной нотации, т.е. не имеют скобках после себя, она не заменяется на всех.
Original:
Function-like macros replace each occurrence of defined identifier with replacement-list, additionally taking a number of arguments, which then replace corresponding occurrences of any of the parameters in the replacement-list. The number of arguments must be the same as the number of arguments in macro definition (parameters) or the program is ill-formed. If the identifier is not in functional-notation, i.e. does not have parentheses after itself, it is not replaced at all.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Версия (2) из
#define директива определяет простую функцию, как макро.Original:
Version (2) of the
#define directive defines a simple function-like macro.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Версии (3) из
#define директива определяет функцию, как макрос с переменным числом аргументов. Дополнительных аргументов можно получить с помощью __VA_ARGS__ идентификатор, который затем заменили аргументы, поставляемых с идентификатором быть заменены.Original:
Version (3) of the
#define directive defines a function-like macro with variable number of arguments. The additional arguments can be accessed using __VA_ARGS__ identifier, which is then replaced with arguments, supplied with the identifier to be replaced.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Версия (4),
#define директива определяет функцию, как макрос с переменным числом аргументов, но не регулярные аргументы. Аргументы могут быть доступны только с __VA_ARGS__ идентификатор, который затем заменили аргументы, поставляется с идентификатором быть заменены.Original:
Version (4) of the
#define directive defines a function-like macro with variable number of arguments, but no regular arguments. The arguments can be accessed only with __VA_ARGS__ identifier, which is then replaced with arguments, supplied with identifier to be replaced.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[править] NJ и NJ операторов
В функции подобных макросов,
# оператора до идентификатор в replacement-list работает идентификатор через параметр замены и охватывает результат в кавычки, фактически создав строковый литерал. Кроме того, препроцессор добавляет backslahes, чтобы избежать кавычки вокруг встроенные строковые литералы, если таковые имеются, и удваивает обратную косую черту в строке по мере необходимости. Все начальные и конечные пробелы удаляются, и любая последовательность пробелов в середине текста (но не внутри встроенных литералов строка) рухнул на одном пространстве. Эта операция называется "стрингификации". Если результат стрингификации не является допустимым строковый литерал, поведение не определено.Original:
In function-like macros, a
# operator before an identifier in the replacement-list runs the identifier through parameter replacement and encloses the result in quotes, effectively creating a string literal. In addition, the preprocessor adds backslahes to escape the quotes surrounding embedded string literals, if any, and doubles the backslashes within the string as necessary. All leading and trailing whitespace is removed, and any sequence of whitespace in the middle of the text (but not inside embedded string literals) is collapsed to a single space. This operation is called "stringification". If the result of stringification is not a valid string literal, the behavior is undefined.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
## оператора между любыми двумя последовательными идентификаторы в replacement-list работает параметров замены на двух идентификаторов, а затем объединяет результаты. Эта операция называется "объединение" или "знак вставки". Только жетоны, которые образуют действительный маркер вместе, могут быть вставлены: идентификаторы, которые формируют более идентификатор, цифры, которые образуют число, или операторы + и =, что форма +=. Комментарий не может быть создано путем вставки / и *, потому что комментарии будут удалены из текста перед макроподстановки считается. Если в результате объединения не является допустимым маркером, поведение не определено.Original:
A
## operator between any two successive identifiers in the replacement-list runs parameter replacement on the two identifiers and then concatenates the result. This operation is called "concatenation" or "token pasting". Only tokens that form a valid token together may be pasted: identifiers that form a longer identifier, digits that form a number, or operators + and = that form a +=. A comment cannot be created by pasting / and * because comments are removed from text before macro substitution is considered. If the result of concatenation is not a valid token, the behavior is undefined.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[править] NJ директивы
#undef директивы undefines identifier, который отменяет предыдущее определение identifier по #define директивы. Если идентификатор не были связаны макроса, директива игнорируется.Original:
The
#undef directive undefines the identifier, that is cancels previous definition of the identifier by #define directive. If the identifier does not have associated macro, the directive is ignored.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[править] Предопределенные макросы
Следующие имена макросов являются предопределенными в любой единице трансляции.
Original:
The following macro names are predefined in any translation unit.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
| __cplusplus |
расширяется до значения 199711L(до C++11) или 201103L(начиная с C++11) Original: expands to value 199711L(до C++11) or 201103L(начиная с C++11) The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (константа-макрос) |
| __STDC_HOSTED__ (C++11) |
расширяется до целочисленной константы 1, если реализация размещается (работает под ОС), если автономные 0 (работает без ОС) Original: expands to the integer constant 1 if the implementation is hosted (runs under an OS), 0 if freestanding (runs without an OS) The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (константа-макрос) |
| __FILE__ |
расширяется в имя текущего файла, а строковый литерал Original: expands to the name of the current file, as a character string literal The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (константа-макрос) |
| __LINE__ |
расширяется до строки исходного файла, целая константа Original: expands to the source file line number, an integer constant The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (константа-макрос) |
| __DATE__ |
расширяется до даты перевода, строковый литерал в форме "Ммм дд гггг". Название месяца, как если бы порожденный std::asctime() Original: expands to the date of translation, a character string literal of the form "Mmm dd yyyy". The name of the month is as if generated by std::asctime() The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (константа-макрос) |
| __TIME__ |
расширяется до момента перевода, строковый литерал в форме "чч: мм: сс" Original: expands to the time of translation, a character string literal of the form "hh:mm:ss" The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (константа-макрос) |
Следующие дополнительные имена макросов может быть предопределен реализации.
Original:
The following additional macro names may be predefined by the implementations.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
| __STDC__ |
осуществление определенного значения, если они присутствуют Original: implementation-defined value, if present The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (константа-макрос) |
| __STDC_VERSION__ (C++11) |
осуществление определенного значения, если они присутствуют Original: implementation-defined value, if present The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (константа-макрос) |
| __STDC_ISO_10646__ (C++11) |
расширяется до целого числа постоянных вид yyyymmL, если wchar_t использует Unicode, дата указывает на последнюю версию Unicode поддерживаетсяOriginal: expands to an integer constant of the form yyyymmL, if wchar_t uses Unicode, the date indicates the latest revision of Unicode supportedThe text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (константа-макрос) |
| __STDC_MB_MIGHT_NEQ_WC__ (C++11) |
расширяется до 1 если широкая кодировку основного набора символов может не совпадать своих узких кодирования Original: expands to 1 if wide character encoding of the basic character set may not equal their narrow encoding The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (константа-макрос) |
| __STDCPP_STRICT_POINTER_SAFETY__ (C++11) |
расширяется до 1, если реализация имеет строгие std::pointer_safety Original: expands to 1 if the implementation has strict std::pointer_safety The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (константа-макрос) |
| __STDCPP_THREADS__ (C++11) |
расширяется до 1 если программа может иметь более одного потока исполнения Original: expands to 1 if the program can have more than one thread of execution The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. (константа-макрос) |
Значения этих макросов (за исключением
__FILE__ и __LINE__) остаются постоянными на протяжении всего ЕП. Попытки пересмотреть или неопределенное этих макросов приведет к неопределенному поведению.Original:
The values of these macros (except for
__FILE__ and __LINE__) remain constant throughout the translation unit. Attempts to redefine or undefine these macros result in undefined behavior.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Примечание: в комплект каждой функции тела, есть специальная функция-местный предопределенных переменная с именем __func__(начиная с C++11), определяется как статический массив символов проведение имя функции в реализации определенного формата. Это не макрос препроцессора, но она используется вместе с
__FILE__ и __LINE__, например, по assert.Original:
Note: in the scope of every function body, there is a special function-local predefined variable named __func__(начиная с C++11), defined as a static character array holding the name of the function in implementation-defined format. It is not a preprocessor macro, but it is used together with
__FILE__ and __LINE__, e.g. by assert.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[править] Пример
#include <iostream> //make function factory and use it #define FUNCTION(name, a) int fun_##name() { return a;} FUNCTION(abcd, 12); FUNCTION(fff, 2); FUNCTION(kkk, 23); #undef FUNCTION #define FUNCTION 34 #define OUTPUT(a) std::cout << #a << '\n' int main() { std::cout << "abcd: " << fun_abcd() << '\n'; std::cout << "fff: " << fun_fff() << '\n'; std::cout << "kkk: " << fun_kkk() << '\n'; std::cout << FUNCTION << '\n'; OUTPUT(million); //note the lack of quotes }
Вывод:
abcd: 12 fff: 2 kkk: 23 34 million