Skip to content

Commit c5b5207

Browse files
author
Michael Blome
committed
new file for constexpr lambdas
1 parent dcd787d commit c5b5207

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
---
2+
title: "constexpr Lambda Expressions in C++ | Microsoft Docs"
3+
ms.custom: ""
4+
ms.date: "07/19/2017"
5+
ms.reviewer: ""
6+
ms.suite: ""
7+
ms.technology:
8+
- "cpp-language"
9+
ms.tgt_pltfrm: ""
10+
ms.topic: "language-reference"
11+
dev_langs:
12+
- "C++"
13+
helpviewer_keywords:
14+
- "lambda expressions [C++], constexpr"
15+
ms.assetid: b56346cd-fbff-475f-aeaa-ed2010c6d6f7
16+
caps.latest.revision: 0
17+
author: "mikeblome"
18+
ms.author: "mblome"
19+
manager: "ghogen"
20+
---
21+
# constexpr Lambda Expressions in C++
22+
In Visual Studio 2017 version 15.3 and later, a lambda expression may be declared as `constexpr` or used in a contant expression when the initialization of each data member that it captures or introduces is allowed within a constant expression.
23+
24+
```cpp
25+
int y = 32;
26+
auto answer = [y]() constexpr
27+
{
28+
int x = 10;
29+
return y + x;
30+
};
31+
32+
constexpr int Increment(int n)
33+
{
34+
return [n] { return n + 1; }();
35+
}
36+
37+
```
38+
A lambda is implicitly `constexpr` if its result satisfies the requirements of a `constexpr` function:
39+
```cpp
40+
auto answer = [](int n)
41+
{
42+
return 32 + n;
43+
};
44+
45+
constexpr int response = answer(10);
46+
```
47+
If a lambda is implicitly or explicitly `constexpr`, and you convert it to a function pointer, the resulting function is also `constexpr`:
48+
49+
```cpp
50+
auto Increment = [](int n)
51+
{
52+
return n + 1;
53+
};
54+
55+
constexpr int(*inc)(int) = Increment;
56+
```
57+
58+
## See Also
59+
[C++ Language Reference](../cpp/cpp-language-reference.md)
60+
[Function Objects in the C++ Standard Library](../standard-library/function-objects-in-the-stl.md)
61+
[Function Call](../cpp/function-call-cpp.md)
62+
[for_each](../standard-library/algorithm-functions.md#for_each)

0 commit comments

Comments
 (0)