Home > OS >  Where to position this vector?
Where to position this vector?

Time:01-03

I have constructed a minimal "working" example - If you comment out all the references to items_ then the code compiles and executes fine. I have to populate a vector from inside a friend method and then access those contents from another object from a different class.

#include <array>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <optional>
#include <set>
#include <set>
#include <vector>

namespace autodiff {
namespace base {
class var {
public:
    friend var operator (const var& l, const var& r) {
        var result;
        // need to populate items_ here!
        items_.push_back(result.left_);
        items_.push_back(result.right_);
        // ... 
        return result;
    }

private:
    std::shared_ptr<var> left_;
    std::shared_ptr<var> right_;
};

static std::vector<std::shared_ptr<var>> items_;

class expression {
public:
    expression(var v) {
        // need items here!!
        for (const auto& i : items_) {
            // need to do stuff with items_ in here...
        }
    };

}  // namespace base
}  // namespace autodiff

I have tried moving the static vector to various locations but the same error keeps appearing:

‘items_’ was not declared in this scope

This is obvious to me. Putting it above var or below it doesn't make sense. However, I can't think of a workaround. I have tried to put it in a namespace.

CodePudding user response:

Option 1: define items_ before all these classes, write class var; (just that line) before it. Option 2: move method definitions down below, after items_. Option 3: make items_ a static field. Option 4: get rid of items_ altogether; I don't know what you're trying to achieve, but I suspect you don't really need to store a copy of each element happening in an expression, an expression can own all of its children.

– answer by yeputons

  •  Tags:  
  • c
  • Related