Skip to content

Instantly share code, notes, and snippets.

@zzh8829
Created January 18, 2014 02:47
Show Gist options
  • Select an option

  • Save zzh8829/9d4744a7b7e3e0927d12 to your computer and use it in GitHub Desktop.

Select an option

Save zzh8829/9d4744a7b7e3e0927d12 to your computer and use it in GitHub Desktop.
C++ Lightning Fast Function Wrapper
template<typename T>
class Delegate{};
template<typename Return, typename ... Args>
class Delegate<Return(Args ...)>
{
private:
class AnyClass;
using AnyMemberFunc = Return(AnyClass::*)(Args...);
using AnyStaticFunc = Return(*)(Args...);
AnyClass* object_ = nullptr;
AnyMemberFunc member_func_ = nullptr;
AnyStaticFunc static_func_ = nullptr;
public:
inline Delegate() = default;
template<typename Class, typename MemberFunc>
inline Delegate(Class* object,MemberFunc func)
{
Bind(object,func);
}
inline Delegate(AnyStaticFunc func)
{
Bind(func);
}
template<typename Class, typename MemberFunc>
inline void Bind(Class* object, MemberFunc func)
{
this->object_ = reinterpret_cast<AnyClass*>(object);
this->member_func_ = reinterpret_cast<AnyMemberFunc>(func);
this->static_func_ = nullptr;
}
inline void Bind(AnyStaticFunc func)
{
this->object_ = nullptr;
this->member_func_ = nullptr;
this->static_func_ = func;
}
inline Return operator()(Args... args) const
{
if(static_func_) return (*(static_func_))(std::forward<Args>(args)...);
return (object_->*member_func_)(std::forward<Args>(args)...);
}
inline std::size_t Hash() const
{
if(static_func_) return reinterpret_cast<std::size_t>(static_func_);
return
reinterpret_cast<std::size_t>(object_) ^
reinterpret_cast<std::size_t>(member_func_);
}
inline bool operator==(const Delegate& delegate) const
{
if(static_func_ || delegate.static_func_ ) return this->static_func_ == delegate.static_func_;
return
this->object_ == delegate.object_ &&
this->member_func_ == delegate.member_func_;
}
inline bool operator!=(const Delegate& delegate) const {return !operator==(delegate);}
};
namespace std {
template<typename Return, typename ... Args>
struct hash<Delegate<Return(Args...)> >
{
std::size_t operator()(const Delegate<Return(Args...)>& delegate) const
{
return delegate.Hash();
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment