Howto check a type for the existence of parameterless operator()

前端 未结 2 1481
北荒
北荒 2021-02-06 09:33

I\'m trying to check whether a functor is compatible with a given set of parametertypes and a given return type (that is, the given parametertypes can be implicitely converted t

2条回答
  •  后悔当初
    2021-02-06 10:31

    Have you tried something like:

    template
    class Discrim
    {
    };
    
    template
    std::true_type hasFunctionCallOper( T*, Discrim* );
    
    template
    std::false_type hasFunctionCallOper( T*, ... );
    

    After, you discriminate on the return type of hasFunctionCallOper((T*)0, 0).

    EDITED (thanks to the suggestion of R. Martinho Fernandes):

    Here's the code that works:

    template
    class CallOpDiscrim {};
    
    template
    TrueType hasCallOp( T*, CallOpDiscrim< sizeof( (*((T const*)0))(), 1 ) > const* );
    template
    FalseType hasCallOp( T* ... );
    
    template
    class TestImpl;
    
    template
    class TestImpl
    {
    public:
        void doTellIt() { std::cout << typeid(T).name() << " does not have operator()" << std::endl; }
    };
    
    template
    class TestImpl
    {
    public:
        void doTellIt() { std::cout << typeid(T).name() << " has operator()" << std::endl; }
    };
    
    template
    class Test : private TestImpl(0, 0)) == sizeof(TrueType)>
    {
    public:
        void tellIt() { this->doTellIt(); }
    };
    

提交回复
热议问题