【问题标题】:Syntax of C++ templates with function type parameters带有函数类型参数的 C++ 模板的语法
【发布时间】:2011-11-06 21:31:46
【问题描述】:

我习惯于看到这样的函数指针语法

int (*pointer_name) (float, char *);
void call_function (void (*)(int), int);

在一些 C++03 函数库中,我看到使用这种方式的类型:

abc::function<void(*)(int,float)> f;

在 C++11 的 std::function 中,我看到了以这种方式给出的类型

std::function<void(int,float)> f;

缺少(*)。为什么?

C++03 function&lt;T&gt;T 与对应的函数指针的类型相同。很容易想象它的实现。

核心语言增强支持 C++11 中的std::function。是否扩展了模板参数类型以适应可调用性?

【问题讨论】:

    标签: c++ templates c++11 std-function


    【解决方案1】:

    std::function(及其灵感,boost::function)不仅存储函数指针。它还可以存储函数对象。从这个意义上说,将 函数签名 作为模板参数传递类似于智能指针通常将 pointee 的类型作为模板参数,而不是指针类型!

    对比度:

    int* p; // indirection to an object of type int
    std::unique_ptr<int> q; // indirection to an object of type int
    

    typedef void signature_type(); // a function type
    
    // indirection to something callable with signature_type as a signature
    // i.e. f() has type void
    // only work for freestanding functions however
    signature_type* f;
    
    // indirection to something callable with signature_type as a signature
    // i.e. g() has type void
    // not restricted to function pointers!
    std::function<signature_type> g;
    

    这是一个有用的约定。

    【讨论】:

    • 这比教科书的指针语法好太多了!我想知道为什么我们通常不这样教它......
    • @spraff:可能是因为它是一项相对较新的创新,而且大多数教科书的更新速度都很慢。我仍然看到人们使用 Borland Turbo C++ 学习,这似乎对这种语法有很大的麻烦。
    【解决方案2】:

    这里没有什么魔法,类型

    void(int,float)
    

    是没有名称的函数的类型。它匹配像void g(int x, float y) 这样的函数。

    对于您没有使用函数指针的模板,您也可以使用函数类型。

    【讨论】:

      【解决方案3】:

      与其他元素一样,函数也有类型,您可以在不同的上下文中使用类型或指向类型的指针。您期望的缺少的 (*) 只是 pointer-to 语法。

      int (*pointer_name) (float, char *);
      typedef int my_function_type(float,char*);
      my_function_type * pointer_name2;
      

      pointer_namepointer_name2 的类型相同:指向一个函数的指针,该函数返回int 并接受floatchar* 类型的两个参数。请注意,这完全等同于 int 等其他类型,不同之处在于您不能将变量声明为 function 类型,只能声明 指向函数的指针。 p>

      std::function(或boost::function)的接口只需要函数的签名。 type 参数不是指向函数的指针,而是函数的类型(如上面代码中的my_function_type

      【讨论】:

        【解决方案4】:

        函数类型在 C++11 中并不是新的(参见 C++98 中的 8.3.5)。 IIRC,TR1 和 boost 为 function 提供的改进非常小。

        【讨论】:

          猜你喜欢
          • 2013-01-22
          • 2016-05-16
          • 1970-01-01
          • 2020-03-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多