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

这个接口的关键是该类的用户只需要知道一个公共接口,它接受用户可能抛出的几乎任何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

使用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 );

我没有重新发明轮子,而是引用了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,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,functor_traits< decltype(bind2) >::arity );
    printf("bind arity   X: void(int,1 )   : %i\n",functor_traits< decltype(bindpartial) >::arity );

    return 0;
}

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

所以我的问题是:
如何在不分解std :: bind()结果的情况下确定绑定结果的arity?

我们如何实现尽可能多地支持有界参数的function_traits的完整实现?

解决方法

OP,你的前提是有缺陷的.您正在寻找某种可以告诉您的例程,对于任何给定的对象x,x期望的参数有多少 – 也就是说,x(),x(a)或x(a,b)中的哪一个是 – 形成.

问题是任何数量的替代品可能都是格式良好的!

在a discussion on isocpp.org of this very topic年,Nevin Liber非常正确地写道:

For many function objects and functions,the concepts of arity,parameter type and return type don’t have a single answer,as those things are based on how it [the object] is being used,not on how it has been defined.

这是一个具体的例子.

struct X1 {
    void operator() ()        { puts("zero"); }
    void operator() (int)     { puts("one");  }
    void operator() (int,int) { puts("two");  }
    void operator() (...)     { puts("any number"); }

    template<class... T>
    void operator() (T...)    { puts("any number,the sequel"); }
};

static_assert(functor_traits<X1>::arity == ?????);

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

template<typename F>
struct functor_traits {
    template<int A> static const int has_arity = ?????;
};

…但是如果可以使用一个Foo类型的参数或两个类型为Bar的参数调用它呢?似乎只知道x的(可能的)arity是没有用的 – 它并没有真正告诉你如何调用它.要知道如何调用x,我们需要知道或多或少知道我们要传递给它的类型!

所以,在这一点上,STL至少以一种方式来拯救我们:std :: result_of. (但see here对于基于safer的基于decltype的替代结果;我在这里使用它只是为了方便.)

// std::void_t is coming soon to a C++ standard library near you!
template<typename...> using void_t = void;

template<typename F,typename Enable = void>
struct can_be_called_with_one_int
{ using type = std::false_type; };

template<typename F>  // SFINAE
struct can_be_called_with_one_int<F,void_t<typename std::result_of<F(int)>::type>>
{ using type = std::true_type; };

template<typename F>  // just create a handy shorthand
using can_be_called_with_one_int_t = typename can_be_called_with_one_int<F>::type;

现在我们可以提出像can_be_called_with_one_int_t< int(*)(float)>这样的问题.或can_be_called_with_one_int_t< int(*)(std :: string&)>并得到合理的答案.

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

c 11 – 确定std :: bind()结果的arity和其他特征的标准方法?的更多相关文章

  1. 使用最新的Flurry SDK和ios4重新启动应用程序

    我真的希望这对我来说只是一个愚蠢的错误.我很高兴使用Flurry但这样的事情会导致我的应用被拒绝.解决方法我写了关于这个的Flurry,他们很快回到我身边,他们会调查这个.大约一个星期后,他们回信并表示他们已经在v2.6中修复了它,现在可用了.我似乎无法重现这个问题.不是说我很棒或者什么,但我还是单枪匹马地解决了这个问题.

  2. ios – 类型不符合协议

    我仍然无法理解Swift中泛型的一些微妙之处.我定义了以下类型:viewForValue现在我定义了以下功能.我希望T是一个符合协议SomeProtocol的UIView.但是,当我执行代码时,我收到以下编译错误:似乎在where子句中我不能指定不实现协议的类.这是为什么?

  3. ios – 将Swift项目转换为易于使用的Cocoapods框架

    编辑1:我更新了项目,因此它已经具有框架结构,我只需要弄清楚我将如何向开发人员提供对自定义部件的访问权限.编辑2:我得到了一个答案,但我认为这个问题可能很容易被误解.目标是使其行为和行为像UICollectionView(与委托,数据源,…

  4. 如何在Xcode 4.1中调试OpenCL内核?

    我有一些OpenCL内核没有做他们应该做的事情,我很想在Xcode中调试它们.这可能吗?当我在我的内核中使用printf()时,OpenCL编译器总是给我一大堆错误.解决方法将格式字符串转换为constchar*似乎可以解决此问题.这适用于Lion:这有上述错误:

  5. ios – 如何在Swift中解包数组元素? (即数组为数组)

    假设我有一个String数组,我想将它映射到一个Int数组我可以使用map功能:Numbers现在是一个Int?数组,但我想要一个Int数组.我知道我可以这样做:但这似乎并不是很迅速.从Int数组转换?对于ArrayofInt,需要使用相当多的样板函数来调用filter和map.有更快捷的方法吗?解决方法更新:Xcode7.2Swift2.1.1

  6. ios – Swift:方法重载只在返回类型上有所不同

    我一直在看Swift类,其中定义了两种方法,它们的返回类型不同.我不习惯使用允许这种语言的语言,所以我去寻找描述它如何在Swift中工作的文档.我在任何地方都找不到任何东西.我本来期望在Swift书中有关于它的整个部分.这记录在哪里?

  7. ios – Swift中没有输入参数的通用函数?

    我有一个通用的Swift函数,如下所示:编译器没有错误,但我不知道如何调用此函数.我试过了:但它不起作用.如何在没有输入参数的情况下在Swift中调用Generic函数?解决方法你需要通过一些调用上下文告诉Swift返回类型是什么:注意,在后一种情况下,只有当someCall采用类似于Any的模糊类型作为其参数时,才需要这样做.相反,someCall被指定为[Int]作为参数,函数本身提供上下文,你可以只写someCall事实上,有时可以非常推断出背景!

  8. ios – swift函数返回一个Array

    我学习Swift,我可以理解如何创建一个简单的函数,它接收一个Array并返回一个Array.我的代码:我得到的红色错误是:引用通用类型“Array”需要解决方法在SwiftArray中是通用类型,所以你必须指定什么类型的数组包含.例如:如果你希望你的函数是通用的,那么使用:如果您不想指定类型或具有通用功能使用任何类型:

  9. ios – 嵌套递归函数

    我试图做一个嵌套递归函数,但是当我编译时,编译器崩溃.这是我的代码:编译器记录arehere解决方法有趣的…它似乎也许在尝试在定义之前捕获到内部的引用时,它是bailing?以下修复它为我们:当然没有嵌套,我们根本没有任何问题,例如以下工作完全如预期:我会说:报告!

  10. ios – 键入’ViewController’不符合协议’UICollectionViewDataSource’

    解决方法您必须在ViewController类中实现这两个方法:附:–您的函数原型应该与上述函数完全匹配(如果存在,请删除任何’!

随机推荐

  1. 从C到C#的zlib(如何将byte []转换为流并将流转换为byte [])

    我的任务是使用zlib解压缩数据包(已接收),然后使用算法从数据中生成图片好消息是我在C中有代码,但任务是在C#中完成C我正在尝试使用zlib.NET,但所有演示都有该代码进行解压缩(C#)我的问题:我不想在解压缩后保存文件,因为我必须使用C代码中显示的算法.如何将byte[]数组转换为类似于C#zlib代码中的流来解压缩数据然后如何将流转换回字节数组?

  2. 为什么C标准使用不确定的变量未定义?

    垃圾价值存储在哪里,为什么目的?解决方法由于效率原因,C选择不将变量初始化为某些自动值.为了初始化这些数据,必须添加指令.以下是一个例子:产生:虽然这段代码:产生:你可以看到,一个完整的额外的指令用来移动1到x.这对于嵌入式系统来说至关重要.

  3. 如何使用命名管道从c调用WCF方法?

    更新:通过协议here,我无法弄清楚未知的信封记录.我在网上找不到任何例子.原版的:我有以下WCF服务我输出添加5行,所以我知道服务器是否处理了请求与否.我有一个.NET客户端,我曾经测试这一切,一切正常工作预期.现在我想为这个做一个非托管的C客户端.我想出了如何得到管道的名称,并写信给它.我从here下载了协议我可以写信给管道,但我看不懂.每当我尝试读取它,我得到一个ERROR_broKEN_P

  4. “这”是否保证指向C中的对象的开始?

    我想使用fwrite将一个对象写入顺序文件.班级就像当我将一个对象写入文件时.我正在游荡,我可以使用fwrite(this,sizeof(int),2,fo)写入前两个整数.问题是:这是否保证指向对象数据的开始,即使对象的最开始可能存在虚拟表.所以上面的操作是安全的.解决方法这提供了对象的地址,这不一定是第一个成员的地址.唯一的例外是所谓的标准布局类型.从C11标准:(9.2/20)Apointe

  5. c – 编译单元之间共享的全局const对象

    当我声明并初始化一个const对象时.两个cpp文件包含此标头.和当我构建解决方案时,没有链接错误,你会得到什么如果g_Const是一个非const基本类型!PrintInUnit1()和PrintInUnit2()表明在两个编译单元中有两个独立的“g_Const”具有不同的地址,为什么?

  6. 什么是C名称查找在这里? (&amp;GCC对吗?)

    为什么在第三个变体找到func,但是在实例化的时候,原始变体中不合格查找找不到func?解决方法一般规则是,任何不在模板定义上下文中的内容只能通过ADL来获取.换句话说,正常的不合格查找仅在模板定义上下文中执行.因为在定义中间语句时没有声明func,并且func不在与ns::type相关联的命名空间中,所以代码形式不正确.

  7. c – 在输出参数中使用auto

    有没有办法在这种情况下使用auto关键字:当然,不可能知道什么类型的.因此,解决方案应该是以某种方式将它们合并为一个句子.这可用吗?解决方法看起来您希望默认初始化给定函数期望作为参数的类型的对象.您无法使用auto执行此操作,但您可以编写一个特征来提取函数所需的类型,然后使用它来声明您的变量:然后你就像这样使用它:当然,只要你重载函数,这一切都会失败.

  8. 在C中说“推动一切浮动”的确定性方式

    鉴于我更喜欢将程序中的数字保留为int或任何内容,那么使用这些数字的浮点数等效的任意算术最方便的方法是什么?说,我有我想写通过将转换放在解析的运算符树叶中,无需将表达式转化为混乱是否可以使用C风格的宏?应该用新的类和重载操作符完成吗?解决方法这是一个非常复杂的表达.更好地给它一个名字:现在当您使用整数参数调用它时,由于参数的类型为double,因此使用常规的算术转换将参数转换为double用C11lambda……

  9. objective-c – 如何获取未知大小的NSArray的第一个X元素?

    在objectiveC中,我有一个NSArray,我们称之为NSArray*largeArray,我想要获得一个新的NSArray*smallArray,只有第一个x对象…

  10. c – Setprecision是混乱

    我只是想问一下setprecision,因为我有点困惑.这里是代码:其中x=以下:方程的左边是x的值.1.105=1.10应为1.111.115=1.11应为1.121.125=1.12应为1.131.135=1.14是正确的1.145=1.15也正确但如果x是:2.115=2.12是正确的2.125=2.12应为2.13所以为什么在一定的价值是正确的,但有时是错误的?请启发我谢谢解决方法没有理由期望使用浮点系统可以正确地表示您的帖子中的任何常量.因此,一旦将它们存储在一个双变量中,那么你所拥有的确切的一

返回
顶部