Skip to content

Commit 20c0e60

Browse files
committed
Add type_conversion helper and failing unit test
1 parent dd12785 commit 20c0e60

3 files changed

Lines changed: 25 additions & 1 deletion

File tree

include/chaiscript/dispatchkit/type_conversions.hpp

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,19 @@ namespace chaiscript
394394
return std::make_shared<detail::Type_Conversion_Impl<decltype(func)>>(user_type<From>(), user_type<To>(), func);
395395
}
396396

397+
template<typename From, typename To>
398+
Type_Conversion type_conversion()
399+
{
400+
static_assert(std::is_convertible<From, To>::value, "Types are not automatically convertible");
401+
auto func = [](const Boxed_Value &t_bv) -> Boxed_Value {
402+
// not even attempting to call boxed_cast so that we don't get caught in some call recursion
403+
auto to = To{detail::Cast_Helper<const From &>::cast(t_bv, nullptr)};
404+
return chaiscript::Boxed_Value(std::move(to));
405+
};
406+
407+
return std::make_shared<detail::Type_Conversion_Impl<decltype(func)>>(user_type<From>(), user_type<To>(), func);
408+
}
409+
397410
}
398411

399412

src/test_module.cpp

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,8 @@ class Type2
2828
{
2929
public:
3030
Type2(TestBaseType t_bt)
31-
: m_bt(std::move(t_bt))
31+
: m_bt(std::move(t_bt)),
32+
m_str("Hello World")
3233
{
3334
}
3435

@@ -37,8 +38,14 @@ class Type2
3738
return m_bt.val;
3839
}
3940

41+
const char *get_str() const
42+
{
43+
return m_str.c_str();
44+
}
45+
4046
private:
4147
TestBaseType m_bt;
48+
std::string m_str;
4249
};
4350

4451
enum TestEnum
@@ -158,6 +165,9 @@ CHAISCRIPT_MODULE_EXPORT chaiscript::ModulePtr create_chaiscript_module_test_mo
158165
m->add(chaiscript::type_conversion<TestBaseType, Type2>([](const TestBaseType &t_bt) { return Type2(t_bt); }));
159166

160167
m->add(chaiscript::fun(&Type2::get_val), "get_val");
168+
m->add(chaiscript::fun(&Type2::get_str), "get_str");
169+
m->add(chaiscript::type_conversion<const char *, std::string>());
170+
161171
return m;
162172
}
163173

unittests/user_defined_conversions_2.chai

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,4 @@ auto t := TestBaseType();
77
// "get_val()" which exists on the Type2 type
88
assert_equal(t.get_val(), 10);
99

10+
assert_equal(t.get_str().size(), 11);

0 commit comments

Comments
 (0)