2

что означает понятие - «повышения типа аргумента по умолчанию»(default argument promotion) в функциях с переменным числом параметров в с++?

Из данного источника :

https://habr.com/ru/post/430064/ - непонятен момент:

Т.к. в C++ нет понятия «повышения типа аргумента по умолчанию», то фразу

If the parameter parmN is declared with… a type that is not compatible with the type that results after application of the default argument promotions, the behavior is undefined

надо заменить на

If the parameter parmN is declared with… a type that is not compatible with the type that results when passing an argument for which there is no parameter, the behavior is undefined

Последний пункт я даже переводить не стал, чтобы поделиться своей болью. Во-первых, «повышение типа аргумента по умолчанию» в Стандарте C++ осталось [C++17 8.2.2/9]. И во-вторых, я долго ломал голову над смыслом этой фразы, сравнивал со Стандартом С, где все понятно. Только после прочтения N0695 я наконец понял: тут имеется в виду то же самое.

0

1 ответ 1

3

Это преобразования для аргументов функция с переменным числом аргументов, которые применяются по-умолчанию. Перечень таких преобразований можно найти в стандарте:

8.5.1.2 Function call [expr.call]
9 When there is no parameter for a given argument, the argument is passed in such a way that the receiving function can obtain the value of the argument by invoking va_arg (21.11). [Note: This paragraph does not apply to arguments passed to a function parameter pack. Function parameter packs are expanded during template instantiation (17.6.3), thus each such argument has a corresponding parameter when a function template specialization is actually called. —end note ] The lvalue-to-rvalue (7.1), array-to-pointer (7.2), and function-to-pointer (7.3) standard conversions are performed on the argument expression. An argument that has type cv std::nullptr_t is converted to type void* (7.11). After these conversions, if the argument does not have arithmetic, enumeration, pointer, pointer-to-member, or class type, the program is ill-formed. Passing a potentially-evaluated argument of class type (Clause 12) having a non-trivial copy constructor, a non-trivial move constructor, or a non-trivial destructor, with no corresponding parameter, is conditionally-supported with implementation-defined semantics. If the argument has integral or enumeration type that is subject to the integral promotions (7.6), or a floating-point type that is subject to the floating-point promotion (7.7), the value of the argument is converted to the promoted type before the call. These promotions are referred to as the default argument promotions.

Также стоит отметить, что эти преобразования не применяются при передаче параметров в шаблон функции с переменным числом параметров, так как каждое инстанцирование такого шаблона порождает функцию с фиксированными параметрами шаблона. Пример:

/* функция с переменным числом аргументов */
void foo(char const * psz_format, ...) {}

/* шаблон с переменным числом параметров */
template<typename... x_Args>
void bar(char const * psz_format, x_Args... args) {}

short value{};
foo("str", value); // default argument promotion short -> int
bar("str", value); // никаких преобразований, функция принимает short вторым параметром
2
  • Извините, не совсем понял вот это: Так стоит отметить, что эти преобразования не применяются при передаче параметров в шаблон функции с переменным числом параметров, так как каждое инстанцирование такого шаблона порождает функцию с фиксированными параметрами шаблона.
    – BadCatss
    29 мар 2019 в 20:12
  • 1
    @BadCatss Добавил пример. 29 мар 2019 в 20:20

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.