Returning a derived class of a virtual class in C++

断了今生、忘了曾经 提交于 2021-02-11 12:58:52

问题


here's my problem.

I have a template abstract class RandomVariable with pure virtual function operator()()

template<T> 
class RandomVariable<T> {
public:
  virtual T operator()() = 0;
  /* other stuff */
protected:
  T value;
}

I also have a template abstract class Process with pure virtual function operator()()

template<T> 
class Process<T> {
public:
  typedef std::pair<double, T> state; 
  typedef std::list<state> result_type;

  virtual result_type operator()() = 0;
  /* other stuff */
protected:
  result_type trajectory;
}

I can easily write a method returning generating a path and returning the last value of my trajectory.

T GenerateTerminalValue() { 
  this->operator()();
  return value.back().second; 
};  

But it would be much better if, instead of returning type T my function actually returned a functor (ideally derived from RandomVariable) with overloaded operator() generating a path and returning the last value of the trajectory. My best try only led to a Segmentation Fault.

What would be a good way to do this? Thanks.


回答1:


What about using std::function?

#include <functional>

template<typename T>
class MyClass {
public:
    std::function<T()> GenerateTerminalValueFunc() {
        return [this]() {
           this->operator()();
            return value.back().second;
        };
    }
    ...
};

Update: If you want to derive from RandomVariable you could try something like this:

#include <memory>

template<typename T>
class TerminalValueOp : public RandomVariable<T>
{
private:
    MyClass<T>* obj_;
public:
    TerminalValueOp(MyClass<T>* obj) : obj_(obj) {}
    T operator()() {
        obj->operator()();
        return obj->value.back().second;
    }
    ...
};

template<typename T>
class MyClass {
public:
    std::shared_ptr<RandomVariable<T>> GenerateTerminalValueOp() {
        return std::make_shared<TerminalValueOp<T>>(this);
    }
    ...
};


来源:https://stackoverflow.com/questions/22967028/returning-a-derived-class-of-a-virtual-class-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!