创建一个类型特征来检测C ++中的仿函数

时间:2018-04-06 03:31:26

标签: c++ c++17 template-meta-programming functor typetraits

考虑以下自定义定义:

  

仿函数是一个(可能是最终的)(可能是联合)类,公开重载operator()

如何定义类型特征:

template <class T> 
struct is_functor {
    static constexpr bool value = /* something */
};

template <class T>
inline constexpr bool is_functor_v = is_functor<T>::value;
true是这样的仿函数时,

评估为T,而标准false则为C++17

1 个答案:

答案 0 :(得分:0)

这是一次尝试(欢迎非工作反例)

struct _argument {
    template <class T> constexpr operator T&() const& noexcept;
    template <class T> constexpr operator T&&() const&& noexcept;
};

template <class F, class Args = std::tuple<>, std::size_t N = 128, class = void>
struct _min_arity {};

template <class F, template <class...> class T, class... Args, std::size_t N>
struct _min_arity<F, T<Args...>, N, std::enable_if_t<sizeof...(Args) <= N>>
: std::conditional_t<
    std::is_invocable_v<F, Args...>,
    std::integral_constant<std::size_t, sizeof...(Args)>,
    _min_arity<F, std::tuple<Args..., _argument>, N>
> {};

template <class F, class = void, class = void>
struct _has_function_call_operator
: std::false_type
{};

template <class F>
struct _has_function_call_operator<
    F,
    std::enable_if_t<std::is_class_v<F> || std::is_union_v<F>>,
    std::void_t<decltype(_min_arity<F>::value)>
>
: std::true_type
{};

template <class T>
struct is_functor
: std::bool_constant<_has_function_call_operator<T>::value>
{};