Created
March 19, 2016 22:12
-
-
Save ricejasonf/535243026afd75477bed to your computer and use it in GitHub Desktop.
Do Stuff Inside a Function That is Declared Constexpr
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
#include<iostream> | |
struct tag1 { }; | |
struct tag2 { }; | |
struct tag3 { }; | |
struct tag4 { }; | |
template <typename Tag> | |
struct foo_impl { }; | |
template <typename Tag> | |
constexpr auto foo(Tag) | |
{ | |
return foo_impl<Tag>::apply(); | |
}; | |
template <> | |
struct foo_impl<tag1> | |
{ | |
static constexpr int apply() | |
{ | |
return 5; | |
} | |
}; | |
template <> | |
struct foo_impl<tag2> | |
{ | |
static int apply() | |
{ | |
std::cout << "Do something not constexpr friendly.\n"; | |
return 5; | |
} | |
}; | |
template <> | |
struct foo_impl<tag3> | |
{ | |
static int apply() | |
{ | |
return ([](int x) { return x; })(5); | |
} | |
}; | |
template <> | |
struct foo_impl<tag4> | |
{ | |
static int apply() | |
{ | |
std::aligned_storage<sizeof(int)> storage; | |
new (&storage) int(5); | |
int x = *reinterpret_cast<int*>(&storage); | |
return x; | |
} | |
}; | |
int main() | |
{ | |
constexpr int x1 = foo(tag1{}); | |
int x2 = foo(tag2{}); | |
int x3 = foo(tag3{}); | |
int x4 = foo(tag4{}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment