zoukankan      html  css  js  c++  java
  • std::function 使用_

     1 #include <iostream>
     2 #include <functional>
     3 
     4 //函数指针写法
     5 typedef int(*FuncPoint)(const int&);
     6 
     7 
     8 std::function<int(const int &)> Function;
     9 
    10 //普通函数
    11 int FuncDemo(const int &value)
    12 {
    13     std::cout << "普通函数	:" << value << "
    ";
    14     return value;
    15 }
    16 
    17 //lamda函数
    18 auto lmdFuc = [](const int &value) -> int
    19 {
    20     std::cout << "lamda函数	:" << value << "
    ";
    21     return value;
    22 };
    23 
    24 //仿函数
    25 class Functor
    26 {
    27 public:
    28     int operator()(const int &value)
    29     {
    30         std::cout << "仿函数	:" << value << "
    ";
    31         return value;
    32     }
    33 };
    34 
    35 //类内静态函数和类成员函数
    36 class Testclass
    37 {
    38 public:
    39     int TestDemo(const int &value)
    40     {
    41         std::cout << "类内成员函数	:" << value << "
    ";
    42         return value;
    43     }
    44 
    45     static int TestStatic(const int &value)
    46     {
    47         std::cout << "类内静态成员函数	:" << value << "
    ";
    48         return value;
    49     }
    50 };
    51 
    52 
    53 int main()
    54 {
    55     //以往函数指针调用
    56     FuncPoint Func(FuncDemo);
    57     Func(10);
    58     //普通函数
    59     Function = FuncDemo;
    60     Function(10);
    61 
    62     //lamda函数
    63     Function = lmdFuc;
    64     Function(20);
    65 
    66     //仿函数(函数对象)
    67     Functor Fobj;
    68     Function=Fobj;
    69     Function(30);
    70 
    71     //类内成员函数(需要bind())
    72     Testclass testclass;
    73     Function=std::bind(&Testclass::TestDemo,testclass,std::placeholders::_1);
    74     Function(40);
    75 
    76     //类内静态成员函数
    77     Function=Testclass::TestStatic;
    78     Function(50);
    79 
    80 
    81     return 0;
    82 }
    • 关于可调用实体转换为std::function对象需要遵守以下两条原则:
      • 转换后的std::function对象的参数能转换为可调用实体的参数;
      • 可调用实体的返回值能转换为std::function对象的返回值。
    • std::function对象最大的用处就是在实现函数回调,使用者需要注意,它不能被用来检查相等或者不相等,但是可以与NULL或者nullptr进行比较。

    为什么加入std::function;

    好用并实用的东西才会加入标准的。因为好用,实用,我们才在项目中使用它。std::function实现了一套类型消除机制,可以统一处理不同的函数对象类型。以前我们使用函数指针来完成这些;现在我们可以使用更安全的std::function来完成这些任务。

  • 相关阅读:
    Notification 通知
    首次在MI5手机上看到APP界面 ~
    Installation falied with message Failed to establish session.
    adb.exe 已停止工作
    内容提供器(Content Provider)
    Android 数据存储
    RecyclerView
    UI设计 四种基本布局
    关于Android教学的思考1
    Android 主要控件
  • 原文地址:https://www.cnblogs.com/xuaidongstdudyrecording/p/6503181.html
Copyright © 2011-2022 走看看