0

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.

AFK
  • 99
  • 3

1 Answers1

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);
    }
    ...
};
Danvil
  • 22,240
  • 19
  • 65
  • 88
  • Your solution is really simple and works fine. One question though, I'm a beginner in C++ and I have never encountered the bracketed keyword [this], what is its meaning exactly? Also what would you do if you really wanted your return type to derive from the RandomVariable class? – AFK Apr 09 '14 at 15:56
  • @YBL The `[this]` you mentioned is just the capture clause of a [lambda expression](http://en.cppreference.com/w/cpp/language/lambda "Lambda expressions on cppreference.com"). Adding the `this` pointer to the capture list basically just gives the lambda expression permission to use it. – Lilshieste Apr 09 '14 at 16:28
  • @Constructor: As T was used in the OP's question, I assumed that this function is part of a template class. – Danvil Apr 09 '14 at 16:34