确定std :: bind()结果的arity和其他特征的标准方法?

use*_*626 7 ambiguous arity stdbind variadic-templates c++11

几天来我一直在试着弄清楚如何让一个类有一个很好的干净的公共接口来执行回调机制的注册.回调可以是C++ 11个lambda表达式,std::function<void(Type1,Type2)>,std::function<void(Type2)>,std::function<void()>,或的结果std::bind().

这个接口的关键是该类的用户只需要知道一个公共接口,它接受用户可能抛出的几乎任何functor/callback机制.

简化的类显示了仿函数和接口的注册

struct Type1;
struct Type2; // May be the same type as Type1
class MyRegistrationClass
{
public:
    /**
     * Clean and easy to understand public interface:
     * Handle registration of any functor matching _any_ of the following
     *    std::function<void(Type1,Type2)>
     *    std::function<void(Type2)>        <-- move argument 2 into arg 1
     *    std::function<void()>
     *    or any result of std::bind() requiring two or fewer arguments that
     *    can convert to the above std::function< ... > types.
     */
    template<typename F>
    void Register(F f) {
       doRegister(f);
    }
private:
    std::list< std::function< void(Type1, Type2) > > callbacks;


    // Handle registration for std::function<void(Type1,Type2)>
    template <typename Functor>
    void doRegister(const Functor & functor,
                           typename std::enable_if< 
                                   !is_bind_expr<Functor>
                                   && functor_traits<decltype(&Functor::operator())>::arity == 2
                               >::type * = nullptr )
    {
        callbacks.push_back( functor );
    }

    // Handle registration for std::function<void(Type2)> by using std::bind
    // to discard argument 2 ...
    template <typename Functor>
    void doRegister(const Functor & functor, 
                           typename std::enable_if< 
                                   !std::is_bind_expression< Functor >::value
                                   && functor_traits<decltype(&Functor::operator())>::arity == 1
                               >::type * = nullptr )
    {
        // bind _2 into functor
        callbacks.push_back( std::bind( functor,                              std::placeholders::_2 ) );
    }

    // Handle registration for std::function<void(Type2)> if given the results
    // of std::bind()
    template <typename Functor>
    void doRegister(const Functor & functor,
                           typename std::enable_if< 
                                   is_bind_expr<Functor>
///////////////////////////////////////////////////////////////////////////
//// BEGIN Need arity of a bounded argument
///////////////////////////////////////////////////////////////////////////
                                   && functor_traits<decltype(Functor)>::arity == 1  
///////////////////////////////////////////////////////////////////////////
//// END need arity of a bounded argument
///////////////////////////////////////////////////////////////////////////
                               >::type * = nullptr )
    {
        // Push the result of a bind() that takes a signature of void(Type2)
        // and push it into the callback list, it will automatically discard
        // argument1 when called, since we didn't bind _1 placeholder
        callbacks.push_back( functor );
    }

    // And other "doRegister" methods exist in this class to handle the other
    // types I want to support ...
}; // end class
Run Code Online (Sandbox Code Playgroud)

使用enable_if <>的复杂性的唯一原因是打开/关闭某些方法.我们必须这样做,因为当我们想要将std :: bind()的结果传递给Register()方法时,如果我们有这样的简单签名,它可以模糊地匹配多个注册方法:

void doRegister( std::function< void(Type1, Type2) > arg );
void doRegister( std::function< void(Type2) > arg ); // NOTE: type2 is first arg
void doRegister( std::function< void() > arg );
Run Code Online (Sandbox Code Playgroud)

我没有重新发明轮子,而是引用了traits.hpp,然后用我自己的名为"functor_traits"的特性帮助器包装它,它增加了对std :: bind()的支持

到目前为止,我已经提出了这个问题来识别有界函数"arity"...或者绑定结果所期望的参数数量的计数:

我试图找到绑定结果arity

#include <stdio.h>
// Get traits.hpp here: https://github.com/kennytm/utils/blob/master/traits.hpp
#include "traits.hpp" 

using namespace utils;
using namespace std;

void f1() {};
int f2(int) { return 0; }
char f3(int,int) { return 0; }

struct obj_func0 
{
    void operator()() {};
};
struct obj_func1
{
    int operator()(int) { return 0; };
};
struct obj_func2 
{
    char operator()(int,int) { return 0; };
};


/**
 * Count the number of bind placeholders in a variadic list
 */
template <typename ...Args>
struct get_placeholder_count
{
    static const int value = 0;
};
template <typename T, typename ...Args >
struct get_placeholder_count<T, Args...>
{
    static const int value = get_placeholder_count< Args... >::value + !!std::is_placeholder<T>::value;
};


/**
 * get_bind_arity<T> provides the number of arguments 
 * that a bounded expression expects to have passed in. 
 *  
 * This value is get_bind_arity<T>::arity
 */

template<typename T, typename ...Args>
struct get_bind_traits;

template<typename T, typename ...Args>
struct get_bind_traits< T(Args...) >
{
    static const int arity = get_placeholder_count<Args...>::value;
    static const int total_args = sizeof...(Args);
    static const int bounded_args = (total_args - arity);
};

template<template<typename, typename ...> class X, typename T, typename ...Args>
struct get_bind_traits<X<T, Args...>>
{
    // how many arguments were left unbounded by bind
    static const int arity        = get_bind_traits< T, Args... >::arity;

    // total arguments on function being called by bind
    static const int total_args   = get_bind_traits< T, Args... >::total_args;

    // how many arguments are bounded by bind:
    static const int bounded_args = (total_args - arity);

    // todo: add other traits (return type, args as tuple, etc
};

/**
 * Define wrapper "functor_traits" that wraps around existing function_traits
 */
template <typename T, typename Enable = void >
struct functor_traits;

// Use existing function_traits library (traits.hpp)
template <typename T>
struct functor_traits<T, typename enable_if< !is_bind_expression< T >::value >::type > :
    public function_traits<T>
{};

template <typename T>
struct functor_traits<T, typename enable_if< is_bind_expression< T >::value >::type >
{
    static const int arity = get_bind_traits<T>::arity;
};

/**
 * Proof of concept and test routine
 */
int main()
{
    auto lambda0 = [] {};
    auto lambda1 = [](int) -> int { return 0; };
    auto lambda2 = [](int,int) -> char { return 0;};
    auto func0 = std::function<void()>();
    auto func1 = std::function<int(int)>();
    auto func2 = std::function<char(int,int)>();
    auto oper0 = obj_func0();
    auto oper1 = obj_func1();
    auto oper2 = obj_func2();
    auto bind0 = bind(&f1);
    auto bind1 = bind(&f2, placeholders::_1);
    auto bind2 = bind(&f1, placeholders::_1, placeholders::_2);
    auto bindpartial = bind(&f1, placeholders::_1, 1);

    printf("action        : signature       : result\n");
    printf("----------------------------------------\n");
    printf("lambda arity 0: [](){}          : %i\n", functor_traits< decltype(lambda0) >::arity );
    printf("lambda arity 1: [](int){}       : %i\n", functor_traits< decltype(lambda1) >::arity );
    printf("lambda arity 2: [](int,int){}   : %i\n", functor_traits< decltype(lambda2) >::arity );
    printf("func arity   0: void()          : %i\n", functor_traits< function<void()> >::arity );
    printf("func arity   1: int(int)        : %i\n", functor_traits< function<void(int)> >::arity );
    printf("func arity   2: char(int,int)   : %i\n", functor_traits< function<void(int,int)> >::arity );
    printf("C::operator()() arity 0         : %i\n", functor_traits< decltype(oper0) >::arity );
    printf("C::operator()(int) arity 1      : %i\n", functor_traits< decltype(oper1) >::arity );
    printf("C::operator()(int,int) arity 2  : %i\n", functor_traits< decltype(oper2) >::arity );
///////////////////////////////////////////////////////////////////////////
// Testing the bind arity below:
///////////////////////////////////////////////////////////////////////////
    printf("bind arity   0: void()          : %i\n", functor_traits< decltype(bind0) >::arity );
    printf("bind arity   1: int(int)        : %i\n", functor_traits< decltype(bind1) >::arity );
    printf("bind arity   2: void(int,int)   : %i\n", functor_traits< decltype(bind2) >::arity );
    printf("bind arity   X: void(int, 1 )   : %i\n", functor_traits< decltype(bindpartial) >::arity );

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

虽然这个实现在使用libstdc ++的gcc中工作,但我不太确定这是否是一个可移植的解决方案,因为它试图分解std :: bind()的结果......几乎是私有的"_Bind"类,我们真的不应该这样做不需要像libstdc ++的用户那样做.

所以我的问题是: 如何在不分解std :: bind()的结果的情况下确定绑定结果的arity?我们怎样才能实现全面实施function_traits的是尽可能多的支持有限论据可能吗?

Quu*_*one 3

OP,你的前提有缺陷。您正在寻找某种例程,它可以告诉您,对于任何给定的对象x,有多少个参数x需要 \xe2\x80\x94 ,即x()x(a)或中的哪x(a,b)一个是格式良好的。

\n\n

问题是任意数量的这些替代方案都可能是格式良好的!

\n\n

isocpp.org 上关于这个主题的讨论中,Nevin Liber 非常正确地写道:

\n\n
\n

对于许多函数对象和函数,元数、参数类型和返回类型的概念没有单一的答案,因为这些东西取决于它[对象]的使用方式,而不是基于它的定义方式。

\n
\n\n

这是一个具体的例子。

\n\n
struct X1 {\n    void operator() ()        { puts("zero"); }\n    void operator() (int)     { puts("one");  }\n    void operator() (int,int) { puts("two");  }\n    void operator() (...)     { puts("any number"); }\n\n    template<class... T>\n    void operator() (T...)    { puts("any number, the sequel"); }\n};\n\nstatic_assert(functor_traits<X1>::arity == ?????);\n
Run Code Online (Sandbox Code Playgroud)\n\n

因此,我们实际可以实现的唯一接口是提供实际参数计数的接口,并询问是否x可以使用该数量的参数进行调用。

\n\n
template<typename F>\nstruct functor_traits {\n    template<int A> static const int has_arity = ?????;\n};\n
Run Code Online (Sandbox Code Playgroud)\n\n

...但是如果可以使用一个类型参数Foo 两个类型参数来调用它Bar呢?似乎只知道(可能的)数量是x没有用的 \xe2\x80\x94 它并没有真正告诉你如何调用它。要知道如何调用x,我们需要或多或少地知道我们试图传递给它的类型!

\n\n

因此,此时,STL 至少以一种方式来拯救我们:std::result_of。(但是请参阅此处以获取基于更安全的 decltype替代方案result_of;我在这里使用它只是为了方便。)

\n\n
// std::void_t is coming soon to a C++ standard library near you!\ntemplate<typename...> using void_t = void;\n\ntemplate<typename F, typename Enable = void>\nstruct can_be_called_with_one_int\n{ using type = std::false_type; };\n\ntemplate<typename F>  // SFINAE\nstruct can_be_called_with_one_int<F, void_t<typename std::result_of<F(int)>::type>>\n{ using type = std::true_type; };\n\ntemplate<typename F>  // just create a handy shorthand\nusing can_be_called_with_one_int_t = typename can_be_called_with_one_int<F>::type;\n
Run Code Online (Sandbox Code Playgroud)\n\n

现在我们可以提出诸如can_be_called_with_one_int_t<int(*)(float)>或 之类的问题can_be_called_with_one_int_t<int(*)(std::string&)>并得到合理的答案。

\n\n

can_be_called_with_no_arguments您可以为、...with_Type2、构建类似的特征类...with_Type1_and_Type2,然后使用所有这三个特征的结果来构建您的x行为的完整图像 \xe2\x80\x94 至少是\xe2\x80\x94 的x行为的一部分与您的特定图书馆相关。

\n