Skip to content

Instantly share code, notes, and snippets.

@MattPD
Last active September 22, 2016 09:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save MattPD/2da9a665e43642324303 to your computer and use it in GitHub Desktop.
Save MattPD/2da9a665e43642324303 to your computer and use it in GitHub Desktop.
Boost.Hana: compile-time if demo
// Boost.Hana solution
// issue: http://baptiste-wicht.com/posts/2015/07/simulate-static_if-with-c11c14.html
// docs w/ explanation: http://ldionne.com/hana/#tutorial-introspection-is_valid
#include <iostream>
#include <string>
#include <boost/hana.hpp>
auto has_pop_back = boost::hana::is_valid([](auto && obj) -> decltype(obj.pop_back()) { });
template<typename T>
void decrement_kindof(T & value)
{
boost::hana::if_
(
has_pop_back(value),
[](auto & value) { return value.pop_back(); },
[](auto & value) { return --value; }
)(value);
}
int main()
{
std::string s{"abc"};
decrement_kindof(s);
std::cout << s << '\n';
int i = 5;
decrement_kindof(i);
std::cout << i << '\n';
}
$ ./static_if.exe
ab
4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment