Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out if a type has member function with any return type?

I need to find out if a give type has function X as a callable function with a given parameter list. The check should not care about the return value however.

I found this solution from another Stack Overflow question which seems to work well. What it does is this:

#include <type_traits>

template <typename C, typename F, typename = void>
struct is_call_possible : public std::false_type {};

template <typename C, typename R, typename... A>
struct is_call_possible<C, R(A...),
    typename std::enable_if<
        std::is_same<R, void>::value ||
        std::is_convertible<decltype(
            std::declval<C>().operator()(std::declval<A>()...)
        ), R>::value
    >::type
> : public std::true_type {};

This is exactly what I want except that in the check you also supply the desired return type. I was trying to find out a way to modify this to be able to check without taking the return type into account but I couldn't figure out a way.

Does anyone know how to do this?

like image 254
Tobias Avatar asked Apr 30 '14 08:04

Tobias


1 Answers

Just do expression SFINAE and discard the result:

template <typename C, typename... Args>
struct is_call_possible {
private:
    template<typename T>
    static auto check(int)
        -> decltype( std::declval<T>().operator()(std::declval<Args>()...),
                     // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                     // overload is removed if this expression is ill-formed
           std::true_type() );

    template<typename>
    static std::false_type check(...);
public:
    static constexpr bool value = decltype(check<C>(0))::value;
};

Live example.

like image 51
jrok Avatar answered Sep 19 '22 15:09

jrok