-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathif_constexpr.cpp
More file actions
34 lines (30 loc) · 793 Bytes
/
if_constexpr.cpp
File metadata and controls
34 lines (30 loc) · 793 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// if constexpr example
#include <iostream>
#include <type_traits>
template <class T>
void f(T x) {
// if (std::is_floating_point<T>::value) won't compile, as both branches
// should compile
if constexpr (std::is_floating_point<T>::value) {
std::cout << std::abs(x) << '\n';
}
// this branch is discarded at compile time
// should be valid for at least one specialization
else {
std::cout << x << '\n';
}
}
// outside a template, a discarded statement is fully checked. if constexpr is
// not a substitute for the #if preprocessing directive; won't compile as is
/*
void g() {
if constexpr(false) {
int i = 0;
int *p = i; // error even though in discarded statement
}
}
*/
int main() {
f(-2.6);
f("test");
}