Implementing Visitor Pattern while allowing different return types of functions

前端 未结 1 1217
遥遥无期
遥遥无期 2021-01-17 10:14

I am trying to implement the Visitor Pattern for an object structure which has methods with different return types (string, signed int, unsigned int, etc).

Now, in

相关标签:
1条回答
  • 2021-01-17 10:35

    The Accept method in the type hierarchy is just a dispatcher, and has no return type. If what you want is the visitation to produce a value the simplest way would be to add that as part of the state of the visitor:

    struct times2 : visitor {
       double value;
       times2() : value() {}
       void operator()( int x ) { value = x * 2; }
       void operator()( double x ) { value = x * 2; }
    };
    
    object o;
    times2 v;
    o.accept( v );
    std::cout << "Result is " << v.value << std::endl;
    

    Then again, the specific details of the visitor will vary with your implementation, but the idea is that you can store the result in the visitor rather than return it.

    0 讨论(0)
提交回复
热议问题