尝试使用c ++

时间:2020-07-30 21:52:16

标签: c++ pipeline

我正在尝试用c ++在脑海中构建以下内容,但似乎所有内容都没有从Java到c ++的良好翻译,这是我想要实现的目标:

  1. 创建一个流水线,每个步骤都有一个输入和输出(输出将馈送到下一步)
  2. 流程管道首尾相连:
public interface Step<I, O> {
    public static class StepException extends RuntimeException {
        public StepException(Throwable t) {
            super(t);   
        }
    }
    public O process(I input) throws StepException;
}
public class Pipeline<I, O> {
    private final Step<I, O> current;
    private Pipeline(Step<I, O> current) {
        this.current = current;
    }

    private <NewO> Pipeline<I, NewO> pipe(Step<O, NewO> next) {
        return new Pipeline<>(input -> next.process(current.process(input)));
    }
    
    public O execute(I input) throws Step.StepException {
        return current.process(input);
    }
}
public class ExamplePipeline {
    public static class AdditionInput {
        public final int int1;
        public final int int2;
        
        public AdditionInput(int int1, int int2) {
            this.int1 = int1;
            this.int2 = int2;
        }
    }
    public static class AddIntegersStep implements Step<AdditionInput, Integer> {
        public Integer process(AdditionInput input) {
            return input.int1 + input.int2;   
        }
    }
    
    public static class IntToStringStep implements Step<Integer, String> {
        public String process(Integer input) {
            return input.toString();
        }
    }
    
    public static void main(String[] args) {
        Pipeline<AdditionInput, String> pipeline = new Pipeline<>(new AddIntegersStep())
            .pipe(new IntToStringStep());
        System.out.println(pipeline.execute(new AdditionInput(1, 3))); // outputs 4
    }
}

如何在c ++中为上述模型建模?

我无法对管道进行建模,步骤非常简单:

template <typename I>
template <typename O>
class Step {
  virtual O process(I input) = 0;

 public:
  typedef I inputType;
  typedef O outputType;
}

2 个答案:

答案 0 :(得分:2)

我认为可以通过多种方式解决此问题。这是使用lambda的方法:

auto pipe = [](auto a, auto b){ return [&](auto c){ return b(a(c)); }; };

以及使用它的示例程序:

#include <iostream>
#include <string>

auto pipe = [](auto a, auto b){ return [&](auto c){ return b(a(c)); }; };

int main() {
    auto Addition = [](std::pair<int, int> p) {return p.first + p.second;};
    auto IntToString = [](int a) {return std::to_string(a);};
    auto AddNewline = [](std::string a) {return a + "\n";};

    auto pipeline = pipe(pipe(Addition, IntToString), AddNewline);

    std::cout << pipeline(std::pair<int, int>{1, 3});
}

另一种有趣的方法可以在this answer中找到使用|运算符创建管道的方法。

答案 1 :(得分:0)

有多种方法可以执行此操作,具体取决于解决方案的灵活性,快速性或简单性。

如果您不需要在运行时在管道中构建/存储各个步骤以供以后调用,则可以执行与Java示例非常相似的操作,例如将每个步骤建模为可调用类型,然后使用您的pipe成员函数是一个模板,该模板应用作为参数传递的步骤。

相关问题