Added try_implicit_cast<>() to check callbacks validness at run time

This commit is contained in:
Pavel Kirienko
2014-03-09 13:47:07 +04:00
parent 0afb7f4eea
commit 1659b5c476
3 changed files with 43 additions and 3 deletions
@@ -9,6 +9,7 @@
#include <stdexcept>
#include <typeinfo>
#include <uavcan/internal/impl_constants.hpp>
#include <uavcan/internal/util.hpp>
namespace uavcan
{
@@ -24,7 +25,8 @@ public:
: obj_(o)
, fun_(f)
{
if (!o || !f)
if (!try_implicit_cast<bool>(o, true) ||
!try_implicit_cast<bool>(f, true))
{
#if UAVCAN_EXCEPTIONS
throw std::runtime_error(typeid(*this).name());
@@ -74,6 +74,39 @@ template<bool> struct BooleanType { };
typedef BooleanType<true> TrueType;
typedef BooleanType<false> FalseType;
/**
* Relations
*/
template <typename T1, typename T2>
class IsImplicitlyConvertibleFromTo
{
template <typename U> static U returner();
struct True_ { char x[2]; };
struct False_ { };
static True_ test(const T2 &);
static False_ test(...);
public:
enum { Result = sizeof(True_) == sizeof(IsImplicitlyConvertibleFromTo<T1, T2>::test(returner<T1>())) };
};
template <typename From, typename To>
struct TryImplicitCastImpl
{
static To impl(const From& from, const To&, TrueType) { return To(from); }
static To impl(const From&, const To& default_, FalseType) { return default_; }
};
template <typename To, typename From>
To try_implicit_cast(const From& from, const To& default_ = To())
{
return TryImplicitCastImpl<From, To>::impl(from, default_,
BooleanType<IsImplicitlyConvertibleFromTo<From, To>::Result>());
}
}
/// Ensure that conditional comilation macros are present
+7 -2
View File
@@ -66,13 +66,18 @@ public:
TimerEventForwarder(Scheduler& node, Functor functor)
: Timer(node)
, functor_(functor)
{ }
{
assert(try_implicit_cast<bool>(functor, true));
}
const Functor& getFunctor() const { return functor_; }
void onTimerEvent(const TimerEvent& event)
{
functor_(event);
if (try_implicit_cast<bool>(functor_, true))
functor_(event);
else
assert(0);
}
};