C++模板函数和lambda表达式的使用

#include <iostream>

using namespace std;

class Tmp1 {
public:
    int foo() { 
        cout << "Tmp1.foo" << endl;
        return ret;
    }

    string walk() {
        cout << "walk" << endl;
        return "cout walk";
    }

    int ret = 1;
};

class Tmp2 {
public:
    int foo() {
        cout << "Tmp2.foo" << endl;
        return ret;
    }

    string run() {
        cout << "run" << endl;
        return "cout run";
    }

    int ret = 2;
};

struct OutPara {
    int ret = 0;
    string desc;
};

template<typename T, typename F>
void print(T t, const F &f) {
    cout << "test" << endl;
    f(t);
}

int main()
{
    Tmp1 t1;
    OutPara out;
    print(t1, [&](Tmp1 &t)->void{
        out.desc = t.walk();
        out.ret = t.foo();
    });
    cout << out.ret << "\t" << out.desc << endl;
    Tmp2 t2;
    print(t2, [&](Tmp2 &t)->void{
        out.desc = t.run();
        out.ret = t.foo();
    });
    cout << out.ret << "\t" << out.desc << endl;
    return 0;
}

输出

test
walk
Tmp1.foo
1       cout walk
test
run
Tmp2.foo
2       cout run
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页