2
0
mirror of https://github.com/boostorg/hana.git synced 2026-02-02 08:52:11 +00:00
Files
hana/example/tutorial/introspection.sfinae.cpp
Louis Dionne 08b3db1708 [Examples] Modularize and use qualified names
This patch modularizes the examples, makes them self-contained and
also uses qualified hana:: names.

Fixes #139
Fixes #126
2015-08-15 17:50:40 +02:00

47 lines
1.0 KiB
C++

/*
@copyright Louis Dionne 2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#include <boost/hana.hpp>
#include <string>
#include <vector>
namespace hana = boost::hana;
struct yes { std::string toString() const { return "yes"; } };
struct no { };
//! [optionalToString.sfinae]
template <typename T>
std::string optionalToString(T const& obj) {
auto maybe_toString = hana::sfinae([](auto&& x) -> decltype(x.toString()) {
return x.toString();
});
return hana::from_maybe("toString not defined", maybe_toString(obj));
}
//! [optionalToString.sfinae]
int main() {
BOOST_HANA_RUNTIME_CHECK(optionalToString(yes{}) == "yes");
BOOST_HANA_RUNTIME_CHECK(optionalToString(no{}) == "toString not defined");
{
//! [maybe_add]
auto maybe_add = hana::sfinae([](auto x, auto y) -> decltype(x + y) {
return x + y;
});
maybe_add(1, 2); // hana::just(3)
std::vector<int> v;
maybe_add(v, "foobar"); // hana::nothing
//! [maybe_add]
}
}