1 // Boost.Convert test and usage example
2 // Copyright (c) 2009-2016 Vladimir Batov.
3 // Use, modification and distribution are subject to the Boost Software License,
4 // Version 1.0. See http://www.boost.org/LICENSE_1_0.txt.
8 #include <boost/convert.hpp>
9 #include <boost/convert/stream.hpp>
10 #include <boost/detail/lightweight_test.hpp>
11 #include <boost/function.hpp>
12 #include <boost/bind.hpp>
14 namespace { namespace local
16 bool called_functor_int;
17 bool called_functor_double;
18 bool called_functor_foo;
19 bool called_function_int;
20 bool called_function_long;
23 struct functor_int { int operator() () const { local:: called_functor_int = true; return INT_MAX; }};
24 struct functor_double { double operator() () const { local::called_functor_double = true; return INT_MAX; }};
25 struct functor_foo { int func (int) const { local:: called_functor_foo = true; return INT_MAX; }};
27 int function_int () { local:: called_function_int = true; return INT_MAX; }
28 long function_long () { local::called_function_long = true; return INT_MAX; }
31 main(int, char const* [])
33 boost::cnv::cstream cnv;
36 int i01 = boost::convert<int>("uhm", cnv).value_or_eval(functor_int());
37 int i02 = boost::convert<int>("uhm", cnv).value_or_eval(functor_double());
38 int i03 = boost::convert<int>("uhm", cnv).value_or_eval(boost::bind(&functor_foo::func, foo, 0));
39 int i04 = boost::convert<int>("uhm", cnv).value_or_eval(function_int);
40 int i05 = boost::convert<int>("uhm", cnv).value_or_eval(function_long);
42 BOOST_TEST(local:: called_functor_int && i01 == INT_MAX);
43 BOOST_TEST(local::called_functor_double && i02 == INT_MAX);
44 BOOST_TEST(local:: called_functor_foo && i03 == INT_MAX);
45 BOOST_TEST(local:: called_function_int && i04 == INT_MAX);
46 BOOST_TEST(local:: called_function_long && i05 == INT_MAX);
48 local:: called_functor_int = false;
49 local::called_functor_double = false;
50 local:: called_functor_foo = false;
51 local:: called_function_int = false;
52 local:: called_function_long = false;
54 boost::convert<int>("uhm", cnv, functor_int());
55 boost::convert<int>("uhm", cnv, functor_double());
56 boost::convert<int>("uhm", cnv, boost::bind(&functor_foo::func, foo, 0));
57 boost::convert<int>("uhm", cnv, function_int);
58 boost::convert<int>("uhm", cnv, function_long);
60 BOOST_TEST(local:: called_functor_int && i01 == INT_MAX);
61 BOOST_TEST(local::called_functor_double && i02 == INT_MAX);
62 BOOST_TEST(local:: called_functor_foo && i03 == INT_MAX);
63 BOOST_TEST(local:: called_function_int && i04 == INT_MAX);
64 BOOST_TEST(local:: called_function_long && i05 == INT_MAX);
68 boost::convert<int>("uhm", cnv, boost::throw_on_failure);
71 catch (boost::bad_optional_access const&)
74 return boost::report_errors();