检查类是否具有签名的函数 [英] Check if class has function with signature

查看:169
本文介绍了检查类是否具有签名的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个网站上有其他答案使用SFINAE但非C ++ 11代码,还有其他人使用C ++ 11代码,如decltypes,使这个过程更容易。但是,我不知道如何检查类是否有具有特定签名的函数。

There are other answers on this site using SFINAE but with non C++11 code, and there are others using C++11 code like decltypes to make this process easier. However, I am not sure how to check if a class has a function with a specific signature.

我想检查一个类是否具有 receive(const Event&)其中事件是调用检查函数时指定的类类型。

I want to check if a class has the function receive(const Event &) where Event is a class type that is specified when calling the check function.

推荐答案

我知道的最好的方法是检查如果你真的可以调用该函数,如果它返回你期望的类型。下面是一个如何检测类 C 是否具有接收方法的示例,该方法需要 const Event& 作为参数,并返回 void 。检测不是关心该方法是否直接在类 C 中实现,或者在 C code>派生自,也不关心是否有其他默认参数。根据需要进行调整。

The best way I know of is checking if you can actually call the function and if it returns the type you expect. Here's an example of how to detect if a class C has a receive method which takes const Event& as a parameter and "returns" void. The detection does not care whether the method is implemented in the class C directly or in some base class that C derives from, neither does it care whether there are further defaulted parameters. Adapt as needed.

template< typename C, typename Event, typename = void >
struct has_receive
  : std::false_type
{};

template< typename C, typename Event >
struct has_receive< C, Event, typename std::enable_if<
    std::is_same<
        decltype( std::declval<C>().receive( std::declval<const Event&>() ) ),
        void
    >::value
>::type >
  : std::true_type
{};

这篇关于检查类是否具有签名的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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