If we have a template metafunction like std::conditional
, we can "select" types based on a boolean compile-time condition. For example:
template < bool CONDITION, typename T, typename U >
struct conditional;
template < typename T, typename U >
struct conditional < true, T, U >
{
using type = T;
};
template < typename T, typename U >
struct conditional < false, T, U >
{
using type = U;
};
const bool whats_big = sizeof( int ) > sizeof( double );
using bigger_type = typename conditional<whats_big , int , double>::type;
My question is: Is there any way to select between a valid type and an invalid type?
Im currently implementing an event class. Events have a sender parameter and variable number of event args:
template<typename SENDER , typename... ARGS>
class event;
So functions with type void(SENDER& , ARGS&...)
could be used as event handlers.
In that case the handlers are called passing a reference to the object wich have raised the event (Throught the sender param).
On the other hand, I want a way to allow sender member functions to be handlers of events, in other words, functions of type void(SENDER::*)(ARGS&...)
.
The problem is that I cannot use a sentence like:
using handler_type = typename conditional<std::is_class<SENDER>::value,void(SENDER::*)(ARGS&...) , void(SENDER& , ARGS&...)>::type;
Because in the case that SENDER
is not a class type, the first type is invalid (Uses a pointer to a member of a non-class type).
You can do it with an extra level of indirection:
template <bool, typename T, typename ...Args>
struct sender_chooser
{
using type = void(*)(T &, Args &...);
};
template <typename T, typename ...Args>
struct sender_chooser<true, T, Args...>
{
using type = void (T::*)(Args &...);
};
template <typename T, typename ...Args>
struct sender_type
{
using type =
typename sender_chooser<std::is_class<T>::value, T, Args...>::type;
};
Usage:
sender_type<MySender, Arg1, Arg2, Arg3>::type
This is is either void (MySender::*)(Arg1 &, Arg2 &, Arg3 &)
if MySender
is a class type, or otherwise void (*)(Sender &, Arg1 &, Arg2 &, Arg3 &)
.
(You might also want to allow unions.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With