c++ - 创建类型特征以检测 C++ 中的仿函数

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

考虑以下自定义定义:

A functor is a (possibly final) (possibly union) class with a publicly overloaded 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;

T 是这样的仿函数时,它的值为 true,否则为 false,在标准 C++17?

最佳答案

这是一次尝试(欢迎使用非工作计数器示例)

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>
{};

关于c++ - 创建类型特征以检测 C++ 中的仿函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49684861/

相关文章:

c++ - CLR ICLRControl::GetCLRManager 失败并出现错误 HOST_E_INVALIDOPERATION

c++ - 如何让定时器在后台保持运行

c++ - 模板模板函数参数

c++ - 当类没有 constexpr 构造函数时简化冗余 std::array 初始化

C++ - 模板 is_Pointer 似乎失败的奇怪情况

c++ - 访问类成员时的性能

c++ - 多维动态内存 vector c++

c++ - 将字节附加到 Visual C++ 中的二进制文件

c++ - 可以在折叠表达式中使用子表达式吗?

c++ - std::optional 与 "unused/default"值的用法