Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

You might use:

#include <iostream>

namespace Detail {
    struct is_callable
    {
        template<typename F, typename... A>
        static decltype(std::declval<F>()(std::declval<A>()...), std::true_type())
        test(int);

        template<typename F, typename... A>
        static std::false_type
        test(...);
    };
} // namespace Detai

template<typename F, typename... A>
using is_callable = decltype(Detail::is_callable::test<F, A...>(0));

struct X {
    int operator ()(int) { return 0; }
};

int main() {
    std::cout << is_callable<X>() << '\n';
    std::cout << is_callable<X, int>() << '\n';
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top