在C ++中返回虚拟类的派生类 [英] Returning a derived class of a virtual class in C++

查看:56
本文介绍了在C ++中返回虚拟类的派生类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的问题.

我有一个模板抽象类RandomVariable,带有纯虚函数operator()()

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;
}

我还有一个模板抽象类Process,带有纯虚函数operator()()

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; 
};  

但是,如果我的函数实际上返回一个函子(理想情况下是从RandomVariable派生),并且带有重载的operator()生成路径并返回轨迹的最后一个值,而不是返回T类型,那会更好得多.我的最佳尝试只会导致细分错误.

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.

推荐答案

使用 std :: function 怎么样?

#include <functional>

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

更新:如果您想从 RandomVariable 派生,可以尝试执行以下操作:

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);
    }
    ...
};

这篇关于在C ++中返回虚拟类的派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆