Почему явный захват переменной constexpr не работает, а отказ от его захвата работаетC++

Программы на C++. Форум разработчиков
Ответить
Гость
 Почему явный захват переменной constexpr не работает, а отказ от его захвата работает

Сообщение Гость »


I wrote the following code that has two lambdas. One of them explicitly captures i while the other doesn't. Note i is constexpr so we don't need to capture it explicitly.

My question is why func(lambda2) doesn't compile while func(lambda) does? Note lambda doesn't explicitly capture i while lambda2 has i in its capture list. Demo

template constexpr auto func(T c) { constexpr auto k = c; return k; }; int main() { constexpr int i = 0; constexpr auto lambda = []()constexpr { constexpr int j = i; return j; }; //compiles constexpr auto lambda2 = ()constexpr { constexpr int j = i; return j; };//compiles constexpr auto a = func(lambda); //compiles as expected constexpr auto b = func(lambda2); //this doesn't compile why? } Clang says:
error: constexpr variable 'k' must be initialized by a constant expression 3 | constexpr auto k = c; | ^ ~ /home/insights/insights.cpp:18:24: note: in instantiation of function template specialization 'func' requested here 18 | constexpr auto b = func(lambda2); //this doesn't compile why? | ^ /home/insights/insights.cpp:3:24: note: function parameter 'c' with unknown value cannot be used in a constant expression 3 | constexpr auto k = c; | ^ /home/insights/insights.cpp:3:24: note: in call to '(lambda at /home/insights/insights.cpp:13:30)(c)' /home/insights/insights.cpp:2:23: note: declared here 2 | constexpr auto func(T c) { | ^

Источник: https://stackoverflow.com/questions/780 ... pturing-it
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C++»