美文网首页
C++11 实现链式调用

C++11 实现链式调用

作者: FredricZhu | 来源:发表于2020-12-24 15:27 被阅读0次

技术点:

  1. 使用std::function实现函数调用
  2. 使用std::result_of获取后一个函数的返回值
  3. 使用lambda表达式封装递归函数调用

程序代码
task.hpp

#ifndef _TASK_HPP_
#define _TASK_HPP_
#include <functional>
#include <type_traits>

template <typename T>
class Task;

template <typename R, typename ... Args>
class Task<R(Args...)> {
public:
    Task(std::function<R(Args...)>&& f): m_func(std::move(f)) {}
    Task(std::function<R(Args...)>& f): m_func(f) {}

    R Run(Args && ... args) {
        return m_func(std::forward<Args>(args)...);
    }

    template <typename F> 
    auto Then(const F& f) -> Task<typename std::result_of<F(R)>::type(Args...)> {
        using return_type = typename std::result_of<F(R)>::type;
        auto func = std::move(m_func);

        return Task<return_type(Args...)>(
            [func, f](Args&& ... args) {
                return f(func(std::forward<Args>(args)...)); 
            }
        );
    }
private:
    std::function<R(Args...)> m_func;

};
#endif

main.cpp

#include "task.hpp"
#include <iostream>
using std::cout;
using std::endl;

#include <cstdlib>

void TestTask() {
    Task<int(int)> task([](int i) {return i;});
    auto result = task.Then([](int i){return i + 1; }).Then([](int i){return i + 2;}) 
        .Then([](int i){return i + 3; }).Run(1);
    
    cout << "result=" << result << endl;  
}

int main(void) {
    TestTask();

    cout << "请按任意键继续..." << endl;
    getchar();
    return 0;
}

Makefile

TAR=main
WORKSPACE_DIR=.
CC:=g++

.PHONY: build clear all

build:
    $(CC) -std=c++11 $(WORKSPACE_DIR)/*.*pp -g -o $(TAR)

all: clear build

clear:
    rm -rf $(TAR)

程序输出如下


图片.png

相关文章

网友评论

      本文标题:C++11 实现链式调用

      本文链接:https://www.haomeiwen.com/subject/wyumnktx.html