22 #include "goby/util/as.h" 26 bool isnan(
double a) {
return a != a; }
41 MyClass(
int a = 0, std::string b =
"") : a(a), b(b) {}
43 bool operator==(
const MyClass& other) {
return (other.a == a) && (other.b == b); }
45 friend std::istream& operator>>(std::istream& is,
MyClass& obj);
46 friend std::ostream& operator<<(std::ostream& os,
const MyClass& obj);
53 std::istream& operator>>(std::istream& is,
MyClass& obj)
60 std::ostream& operator<<(std::ostream& os,
const MyClass& obj)
62 os << obj.a <<
"!" << obj.b;
66 template <
typename A,
typename B>
void is_sane(
A orig)
68 std::cout <<
"Checking type A: " <<
typeid(
A).name() <<
" converting to B: " <<
typeid(
B).name()
70 B converted = as<B>(orig);
71 std::cout <<
"Original: " << orig <<
", converted: " << converted << std::endl;
72 A should_be_orig = as<A>(converted);
73 std::cout <<
"Converted back from B to A: " << should_be_orig << std::endl;
74 assert(should_be_orig == orig);
75 std::cout <<
"ok!" << std::endl;
81 assert(as<int>(
"12") == 12);
82 assert(as<int>(
"12.7") == std::numeric_limits<int>::max());
83 assert(as<int>(
"foo") == std::numeric_limits<int>::max());
84 assert(as<double>(
"12.7") ==
double(12.7));
85 assert(as<float>(
"12.7") ==
float(12.7));
86 assert(as<double>(
"1e3") == 1e3);
87 assert(test::isnan(as<double>(
"nan")));
88 assert(test::isnan(as<double>(
"PIG")));
91 assert(as<MyEnum>(
"1") == FOO);
92 assert(as<MyEnum>(2) == BAR);
93 assert(as<MyEnum>(
"COW") == BAZ);
96 assert(as<bool>(
"TRUE") ==
true);
97 assert(as<bool>(
"true") ==
true);
98 assert(as<bool>(
"trUe") ==
true);
99 assert(as<bool>(
"1") ==
true);
100 assert(as<bool>(
"false") ==
false);
101 assert(as<bool>(
"0") ==
false);
102 assert(as<bool>(
"DOG") ==
false);
103 assert(as<bool>(
"23") ==
false);
105 assert(as<std::string>(
true) == std::string(
"true"));
106 assert(as<std::string>(
false) == std::string(
"false"));
109 assert(as<MyClass>(
"foobar") ==
MyClass());
113 is_sane<int, std::string>(3);
114 is_sane<double, std::string>(3.56302);
115 is_sane<float, std::string>(6.34);
116 is_sane<unsigned, std::string>(12);
117 is_sane<bool, std::string>(
true);
118 is_sane<MyEnum, std::string>(BAR);
119 is_sane<MyClass, std::string>(
MyClass(3,
"cat"));
121 std::cout <<
"all tests passed" << std::endl;