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

我一直在试着弄清楚如何让一个类有一个很好的干净的公共接口来执行回调机制的注册.回调可以是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的行为的一部分与您的特定图书馆相关.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


一.C语言中的static关键字 在C语言中,static可以用来修饰局部变量,全局变量以及函数。在不同的情况下static的作用不尽相同。 (1)修饰局部变量 一般情况下,对于局部变量是存放在栈区的,并且局部变量的生命周期在该语句块执行结束时便结束了。但是如果用static进行修饰的话,该变量便存
浅谈C/C++中的指针和数组(二) 前面已经讨论了指针和数组的一些区别,然而在某些情况下,指针和数组是等同的,下面讨论一下什么时候指针和数组是相同的。C语言标准对此作了说明:规则1:表达式中的数组名被编译器当做一个指向该数组第一个元素的指针; 注:下面几种情况例外 1)数组名作为sizeof的操作数
浅谈C/C++中的指针和数组(一)指针是C/C++的精华,而指针和数组又是一对欢喜冤家,很多时候我们并不能很好的区分指针和数组,对于刚毕业的计算机系的本科生很少有人能够熟练掌握指针以及数组的用法和区别。造成这种原因可能跟现在大学教学以及现在市面上流行的很多C或者C++教程有关,这些教程虽然通俗易懂,
从两个例子分析C语言的声明 在读《C专家编程》一书的第三章时,书中谈到C语言的声明问题,《C专家编程》这本书只有两百多页,却花了一章的内容去阐述这个问题,足以看出这个问题的重要性,要想透彻理解C语言的声明问题仅仅看书是远远不够的,需要平时多实践并大量阅读别人写的代码。下面借鉴《C专家编程》书中的两个
C语言文件操作解析(一)在讨论C语言文件操作之前,先了解一下与文件相关的东西。一.文本文件和二进制文件 文本文件的定义:由若干行字符构成的计算机文件,存在于计算机系统中。文本文件只能存储文件中的有效字符信息,不能存储图像、声音等信息。狭义上的二进制文件则指除开文本文件之外的文件,如图片、DOC文档。
C语言文件操作解析(三) 在前面已经讨论了文件打开操作,下面说一下文件的读写操作。文件的读写操作主要有4种,字符读写、字符串读写、块读写以及格式化读写。一.字符读写 字符读写主要使用两个函数fputc和fgetc,两个函数的原型是: int fputc(int ch,FILE *fp);若写入成功则
浅谈C语言中的位段 位段(bit-field)是以位为单位来定义结构体(或联合体)中的成员变量所占的空间。含有位段的结构体(联合体)称为位段结构。采用位段结构既能够节省空间,又方便于操作。 位段的定义格式为: type [var]:digits 其中type只能为int,unsigned int,s
C语言文件操作解析(五)之EOF解析 在C语言中,有个符号大家都应该很熟悉,那就是EOF(End of File),即文件结束符。但是很多时候对这个理解并不是很清楚,导致在写代码的时候经常出错,特别是在判断文件是否到达文件末尾时,常常出错。1.EOF是什么? 在VC中查看EOF的定义可知: #def
关于VC+ʶ.0中getline函数的一个bug 最近在调试程序时,发现getline函数在VC+ʶ.0和其他编译器上运行结果不一样,比如有如下这段程序:#include &lt;iostream&gt;#include &lt;string&gt;using namespace std;int
C/C++浮点数在内存中的存储方式 任何数据在内存中都是以二进制的形式存储的,例如一个short型数据1156,其二进制表示形式为00000100 10000100。则在Intel CPU架构的系统中,存放方式为 10000100(低地址单元) 00000100(高地址单元),因为Intel CPU
浅析C/C++中的switch/case陷阱 先看下面一段代码: 文件main.cpp#includeusing namespace std;int main(int argc, char *argv[]){ int a =0; switch(a) { case ...
浅谈C/C++中的typedef和#define 在C/C++中,我们平时写程序可能经常会用到typedef关键字和#define宏定义命令,在某些情况下使用它们会达到相同的效果,但是它们是有实质性的区别,一个是C/C++的关键字,一个是C/C++的宏定义命令,typedef用来为一个已有的数据类型
看下面一道面试题:#include&lt;stdio.h&gt;#include&lt;stdlib.h&gt;int main(void) { int a[5]={1,2,3,4,5}; int *ptr=(int *)(&amp;aʱ); printf(&quot;%d,%d&quot;,*(
联合体union 当多个数据需要共享内存或者多个数据每次只取其一时,可以利用联合体(union)。在C Programming Language 一书中对于联合体是这么描述的: 1)联合体是一个结构; 2)它的所有成员相对于基地址的偏移量都为0; 3)此结构空间要大到足够容纳最&quot;宽&quo
从一个程序的Bug解析C语言的类型转换 先看下面一段程序,这段程序摘自《C 专家编程》:#include&lt;stdio.h&gt;int array[]={23,34,12,17,204,99,16};#define TOTAL_ELEMENTS (sizeof(array)/sizeof(ar
大端和小端 嵌入式开发者应该对大端和小端很熟悉。在内存单元中数据是以字节为存储单位的,对于多字节数据,在小端模式中,低字节数据存放在低地址单元,而在大端模式中,低字节数据存放在高地址单元。比如一个定义一个short型的变量a,赋值为1,由于short型数据占2字节。在小端模式中,其存放方式为0X40
位运算和sizeof运算符 C语言中提供了一些运算符可以直接操作整数的位,称为位运算,因此位运算中的操作数都必须是整型的。位运算的效率是比较高的,而且位运算运用好的话会达到意想不到的效果。位运算主要有6种:与(&amp;),或(|),取反(~),异或(^),左移(&gt;)。1.位运算中的类型转换位
C语言文件操作解析(四)在文件操作中除了打开操作以及读写操作,还有几种比较常见的操作。下面介绍一下这些操作中涉及到的函数。一.移动位置指针的函数 rewind函数和fseek函数,这两个函数的原型是:void rewind(FILE *fp); 将位置指针移动到文件首 int fseek(FILE
结构体字节对齐 在用sizeof运算符求算某结构体所占空间时,并不是简单地将结构体中所有元素各自占的空间相加,这里涉及到内存字节对齐的问题。从理论上讲,对于任何变量的访问都可以从任何地址开始访问,但是事实上不是如此,实际上访问特定类型的变量只能在特定的地址访问,这就需要各个变量在空间上按一定的规则排
C语言文件操作解析(二)C语言中对文件进行操作必须首先打开文件,打开文件主要涉及到fopen函数。fopen函数的原型为 FILE* fopen(const char *path,const char *mode) 其中path为文件路径,mode为打开方式 1)对于文件路径,只需注意若未明确给出绝