-
Notifications
You must be signed in to change notification settings - Fork 74
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[312] - Did you know that C++20 added support for Unevaluated asm-dec…
…laration in constexpr functions?
- Loading branch information
1 parent
2bc52e0
commit 9559b46
Showing
3 changed files
with
158 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
<details open><summary>Info</summary><p> | ||
|
||
* Did you know that C++20 added support for Unevaluated asm-declaration in constexpr functions? | ||
|
||
* https://wg21.link/P1668 | ||
|
||
</p></details><details open><summary>Example</summary><p> | ||
|
||
```cpp | ||
constexpr auto get = [](auto value) { | ||
if consteval { | ||
return value; | ||
} else { | ||
auto result = 0; | ||
asm("movl $42, %%eax\n" : "=r" (result) ); | ||
return result; | ||
} | ||
}; | ||
|
||
static_assert(0 == get(0)); | ||
static_assert(4 == get(4)); | ||
static_assert(2 == get(2)); | ||
|
||
consteval auto fn() { | ||
return get(0); | ||
} | ||
|
||
int main(int argc, char**) { | ||
assert(42 == get(0)); | ||
assert(42 == get(argc)); | ||
return fn(); | ||
} | ||
``` | ||
> https://godbolt.org/z/z5jYdsa9P | ||
</p></details><details open><summary>Puzzle</summary><p> | ||
> Can you implement `const_sub_or_asm_add` which subtract given numbers using C++ operators if values can be constant evaluated and adds them using inline assembly otherwise? | ||
```cpp | ||
constexpr auto const_sub_or_asm_add = [](auto lhs, auto rhs) { | ||
return 0; /*TODO*/ | ||
}; | ||
static_assert(1 == const_sub_or_asm_add(2, 1)); | ||
static_assert(-1 == const_sub_or_asm_add(3, 4)); | ||
int main(int argc, char**) { | ||
{ | ||
constexpr auto c = const_sub_or_asm_add(1, 2); | ||
assert(-1 == c); | ||
} | ||
{ | ||
auto c = const_sub_or_asm_add(1, 2); | ||
assert(3 == c); | ||
} | ||
{ | ||
assert(3 == const_sub_or_asm_add(1, 2)); | ||
assert(1 == const_sub_or_asm_add(argc, 0)); | ||
assert(2 == const_sub_or_asm_add(argc, argc)); | ||
} | ||
} | ||
``` | ||
|
||
> https://godbolt.org/z/897a3fn8M |