Telegram Group & Telegram Channel
Что выведет этот код? (C++23)


import std;

constexpr auto make_checker() {
return [](int x) consteval {
return x % 3 == 0 || x % 5 == 0;
};
}

int main() {
auto checker = make_checker();

std::vector numbers{1, 3, 5, 9, 10, 14, 15};

auto filtered = numbers | std::views::filter([&](int x) {
if (std::is_constant_evaluated()) {
std::print("constexpr\n");
}
return checker(x);
});

std::print("Filtered numbers: ");
for (int x : filtered) {
std::print("{} ", x);
}

std::println("");
}


🧠 Подсказка:
consteval делает checker доступным только в compile-time, но мы вызываем его в runtime через лямбду — что произойдёт?

std::is_constant_evaluated() — интересный механизм проверки, вызывается ли код во время компиляции.

Как отреагирует компилятор на попытку вызвать consteval функцию в runtime?


📌 Ответ
Этот код на C++23 не скомпилируется, и что именно здесь происходит.

🔍 Напоминаем ключевой фрагмент кода:

```cpp
constexpr auto make_checker() {
return [](int x) consteval {
return x % 3 == 0 || x % 5 == 0;
};
} ```

- Здесь создаётся лямбда-функция, помеченная как consteval.

- Ключевое слово consteval означает: функция обязана быть вызвана во время компиляции.

🧨 Где ошибка?


auto filtered = numbers | std::views::filter([&](int x) {
return checker(x); // ← ошибка тут
});


checker — это consteval-лямбда.

Но ты вызываешь её внутри лямбды, которая будет работать во время выполнения программы — т.е. в runtime.

Это нарушение правила consteval → нельзя вызывать такие функции в runtime-коде.

Что скажет компилятор?
Компилятор выдаст ошибку компиляции, такую или похожую:

error: call to consteval function '<lambda>(int)' is not a constant expression



📘 Объяснение
consteval ≠ constexpr

constexpr — это могут быть вызваны в runtime, если нужно.

consteval — это всегда и только compile-time.

Когда ты вызываешь checker(x) в main(), ты нарушаешь это правило.

Как можно исправить?
Если ты заменишь consteval на constexpr, код скомпилируется и выполнится:


constexpr auto make_checker() {
return [](int x) constexpr {
return x % 3 == 0 || x % 5 == 0;
};
}

И тогда результат будет:

Filtered numbers: 3 5 9 10 15

Потому что:
- 3 делится на 3
- 5 делится на 5
- 9 делится на 3
- 10 делится на 5
- 15 делится на 3 и 5



tg-me.com/cpluspluc/1026
Create:
Last Update:

Что выведет этот код? (C++23)


import std;

constexpr auto make_checker() {
return [](int x) consteval {
return x % 3 == 0 || x % 5 == 0;
};
}

int main() {
auto checker = make_checker();

std::vector numbers{1, 3, 5, 9, 10, 14, 15};

auto filtered = numbers | std::views::filter([&](int x) {
if (std::is_constant_evaluated()) {
std::print("constexpr\n");
}
return checker(x);
});

std::print("Filtered numbers: ");
for (int x : filtered) {
std::print("{} ", x);
}

std::println("");
}


🧠 Подсказка:
consteval делает checker доступным только в compile-time, но мы вызываем его в runtime через лямбду — что произойдёт?

std::is_constant_evaluated() — интересный механизм проверки, вызывается ли код во время компиляции.

Как отреагирует компилятор на попытку вызвать consteval функцию в runtime?


📌 Ответ
Этот код на C++23 не скомпилируется, и что именно здесь происходит.

🔍 Напоминаем ключевой фрагмент кода:

```cpp
constexpr auto make_checker() {
return [](int x) consteval {
return x % 3 == 0 || x % 5 == 0;
};
} ```

- Здесь создаётся лямбда-функция, помеченная как consteval.

- Ключевое слово consteval означает: функция обязана быть вызвана во время компиляции.

🧨 Где ошибка?


auto filtered = numbers | std::views::filter([&](int x) {
return checker(x); // ← ошибка тут
});


checker — это consteval-лямбда.

Но ты вызываешь её внутри лямбды, которая будет работать во время выполнения программы — т.е. в runtime.

Это нарушение правила consteval → нельзя вызывать такие функции в runtime-коде.

Что скажет компилятор?
Компилятор выдаст ошибку компиляции, такую или похожую:

error: call to consteval function '<lambda>(int)' is not a constant expression



📘 Объяснение
consteval ≠ constexpr

constexpr — это могут быть вызваны в runtime, если нужно.

consteval — это всегда и только compile-time.

Когда ты вызываешь checker(x) в main(), ты нарушаешь это правило.

Как можно исправить?
Если ты заменишь consteval на constexpr, код скомпилируется и выполнится:


constexpr auto make_checker() {
return [](int x) constexpr {
return x % 3 == 0 || x % 5 == 0;
};
}

И тогда результат будет:

Filtered numbers: 3 5 9 10 15

Потому что:
- 3 делится на 3
- 5 делится на 5
- 9 делится на 3
- 10 делится на 5
- 15 делится на 3 и 5

BY C++ Academy


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/cpluspluc/1026

View MORE
Open in Telegram


telegram Telegram | DID YOU KNOW?

Date: |

Traders also expressed uncertainty about the situation with China Evergrande, as the indebted property company has not provided clarification about a key interest payment.In economic news, the Commerce Department reported an unexpected increase in U.S. new home sales in August.Crude oil prices climbed Friday and front-month WTI oil futures contracts saw gains for a fifth straight week amid tighter supplies. West Texas Intermediate Crude oil futures for November rose $0.68 or 0.9 percent at 73.98 a barrel. WTI Crude futures gained 2.8 percent for the week.

How To Find Channels On Telegram?

There are multiple ways you can search for Telegram channels. One of the methods is really logical and you should all know it by now. We’re talking about using Telegram’s native search option. Make sure to download Telegram from the official website or update it to the latest version, using this link. Once you’ve installed Telegram, you can simply open the app and use the search bar. Tap on the magnifier icon and search for a channel that might interest you (e.g. Marvel comics). Even though this is the easiest method for searching Telegram channels, it isn’t the best one. This method is limited because it shows you only a couple of results per search.

telegram from ye


Telegram C++ Academy
FROM USA