How does the template parameter of std::function work? (implementation)

后端 未结 5 1224
没有蜡笔的小新
没有蜡笔的小新 2020-12-07 08:45

In Bjarne Stroustrup\'s home page (C++11 FAQ):

struct X { int foo(int); };

std::function f;
f = &X::foo; //pointer to membe         


        
5条回答
  •  爱一瞬间的悲伤
    2020-12-07 09:34

    To answer the question in the title. The parameter that std::function uses is a nice trick to pass many type parameters as a single template parameter. Those arguments being the argument types and the return type of a function.

    It turns out that std::function tries to type-erase a general functor but that is just coincidence.

    As a matter of fact, once upon a time there were compilers that wouldn't accept such tricks and the boost::function precursor had a portable syntax by which all the parameters could be passed separately:

    Preferred syntax

    boost::function sum_avg;
    

    Portable syntax

    boost::function4 sum_avg;
    

    https://www.boost.org/doc/libs/1_68_0/doc/html/function/tutorial.html#id-1.3.16.5.4

    So that's how the template parameters of std::function work, at the end it is just a trick to make a lot of parameters look like a function call. Function pointers to that type of function are not necessarily involved in the class.

提交回复
热议问题