如何在cocos2d-x类中检查函数的存在?

时间:2014-04-15 08:38:52

标签: c++ templates cocos2d-x sfinae

我有很多来自CCNode子类的节点,其中一些节点具有函数ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)。 现在我的问题是,是否有可能检查他们是否拥有SFINAE的这个特定功能。 我尝试在该主题的帮助下使其工作:Is it possible to write a template to check for a function's existence?但我无法做到。

以下是我所拥有的:

template <typename T>
class hasMethodCCTouchBegan
{
    typedef char yes;
    typedef long no;

    template <typename C> static yes test( decltype(&C::ccTouchBegan) ) ;
    template <typename C> static no test(...);

public:
    enum { value = sizeof(test<T>(0)) == sizeof(yes) };
};

老实说,我不知道该怎么做。

2 个答案:

答案 0 :(得分:0)

template<class C>
decltype(&C::ccTouchBegan, std::true_type())
methodHelper(int);

template<class C>
std::false_type
methodHelper(...);

template<class C>
struct hasMethodCCTouchBegan : decltype(methodHelper<C>(0))
{
};

如果ccTouchBegan超载,则无法工作。如果您想测试是否可以使用某些参数调用ccTouchBegan,那么您可以将&C::ccTouchBegan更改为std::declval<C>().ccTouchBegan(std::declval<CCTouch*>(), std::declval<CCEvent*>())

答案 1 :(得分:0)

我个人使用(在C ++ 11中):

#include <cstdint>

#define DEFINE_HAS_SIGNATURE(traitsName, funcName, signature)               \
    template <typename U>                                                   \
    class traitsName                                                        \
    {                                                                       \
    private:                                                                \
        template<typename T, T> struct helper;                              \
        template<typename T>                                                \
        static std::uint8_t check(helper<signature, &funcName>*);           \
        template<typename T> static std::uint16_t check(...);               \
    public:                                                                 \
        static                                                              \
        constexpr bool value = sizeof(check<U>(0)) == sizeof(std::uint8_t); \
    }

// Create your traits:
DEFINE_HAS_SIGNATURE(has_ccTouchBegan, T::ccTouchBegan, bool (T::*)(CCTouch *, CCEvent *));
相关问题