在有效和无效类型之间选择 [英] Selecting between valid and non-valid types

查看:190
本文介绍了在有效和无效类型之间选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们有一个模板元功能像 std :: conditional ,我们可以基于布尔编译时条件选择类型。例如:

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;

我的问题是:有无法在有效类型和无效类型之间选择?

当前正在实现一个事件类。事件具有发送者参数和事件args的变量号:

Im currently implementing an event class. Events have a sender parameter and variable number of event args:

template<typename SENDER , typename... ARGS>
class event;

因此类型为 void的函数(SENDER&,ARGS& ...) 可以用作事件处理程序。
在这种情况下,处理程序被称为传递一个引用到引发事件的对象(Throught发送方参数)。

另一方面,我想要一种允许发送方成员函数成为事件的处理程序,换句话说,类型 void(SENDER :: *)(ARGS& ...)的函数。

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;

因为在 SENDER 类型类型,第一种类型是无效的(使用指向非类型成员的指针)。

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;
};

用法:

sender_type<MySender, Arg1, Arg2, Arg3>::type

void(MySender :: *)(Arg1& Arg2& Arg3&)如果 MySender 类类型或 void(*)(Sender& amp; Arg1& Arg2& Arg3&)

(您可能还需要允许联合。)

(You might also want to allow unions.)

这篇关于在有效和无效类型之间选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆