C++ std :: function-like模板语法

Smi*_*les 13 syntax templates variadic-templates c++11 std-function

在C++ 11中,您可以像这样实例化std :: function:

std::function<void(int)> f1;
std::function<int(std::string, std::string)> f2;
//and so on
Run Code Online (Sandbox Code Playgroud)

但是虽然网上有大量关于可变参数模板的信息,但我找不到任何关于如何编写std :: function-like模板的文章,这些模板会接受带括号的参数.任何人都可以解释一下语法及其局限性,或者至少指出现有的解释吗?

Rei*_*ica 15

它没有什么特别之处,它是一种普通的功能类型.当您声明这样的函数时:

int foo(char a, double b)
Run Code Online (Sandbox Code Playgroud)

那么它的类型是int (char, double)."展开"各个参数类型和返回类型的一种方法是使用部分模板特化.基本上,std::function看起来像这样:

template <class T>
struct function; // not defined

template <class R, class... A>
struct function<R (A...)>
{
  // definition here
};
Run Code Online (Sandbox Code Playgroud)


Lig*_*ica 5

非常像任何其他模板,因为int(std::string, std::string)它只是一种类型。

这是一个非常简单的编译示例:

template <typename FType>
struct Functor
{
   Functor(FType* fptr) : fptr(fptr) {}

   template <typename ...Args>
   void call(Args... args)
   {
      fptr(args...);
   }

private:
   FType* fptr;
};

void foo(int x, char y, bool z) {}

int main()
{
   Functor<void(int, char, bool)> f(&foo);
   f.call(1, 'a', true);
   //f.call(); // error: too few arguments to function
}
Run Code Online (Sandbox Code Playgroud)

在现实中,你不得不在专业化FTypeReturnType(ArgTypes...),虽然我的天真的例子已经给你,如果你尝试调用它在兼容的方式,你需要验证。