Question

I'm working on a C++ project in Android. What I want to achieve is make an async call in C++, then send the data back over JNI. It's a simple proof of concept, but that also means my C++ knownledge is limited.

I've got all the functionalities working, but wanting to make the C++ side of the project "better" I want to implement an Observer Pattern. I used this as tutorial: http://www.codeproject.com/Articles/328365/Understanding-and-Implementing-Observer-Pattern-in

After adding everything (ofc modified to my project) I'm getting the following compile error: template argument 2 is invalid in the ASubject.h at the line:

std::vector<PoCCplusplus*> list;

Subject h and cpp:

#pragma once
#include <vector>
#include <list>
#include <algorithm>
#include "PoCCplusplus.h"


class ASubject
{
    //Lets keep a track of all the shops we have observing
    std::vector<PoCCplusplus*> list;

public:
    void Attach(PoCCplusplus *cws);
    void Detach(PoCCplusplus *cws);
    void Notify(char *xml);
};

#include "ASubject.h"

using namespace std;

void ASubject::Attach(PoCCplusplus *cws)
{
    list.push_back(cws);
}
void ASubject::Detach(PoCCplusplus *cws)
{
    list.erase(std::remove(list.begin(), list.end(), cws), list.end());
}

void ASubject::Notify(char *xml)
{
    for(vector<PoCCplusplus*>::const_iterator iter = list.begin(); iter != list.end(); ++iter)
    {
        if(*iter != 0)
        {
            (*iter)->Update(xml);
        }
    }
}

It's probably something really simple I'm missing, but I just cant find the solution for it.

Was it helpful?

Solution

  • Rename the list attribute in ASubject to something else , say observedShops (as named in your comment already).
  • Avoid using namespace std in library code.

OTHER TIPS

You

#include <list>

so 'list' is already a defined type. Choose a different variable name.

This is why it's a good idea to not use:

using namespace std;

Also, observer can be done shorter, if you use boost::signals2:

#include <boost/signals2.hpp>
#include <boost/bind.hpp>

using namespace std;
using boost::signals2::signal;
using boost::bind;

struct Some {
    void Update(char* xml) {
        cout << "Update\n";
    }
    void operator()(char* xml) {
        cout << "operator\n";
    }
};

void func(char* xml) {
    cout << "func\n";
}

int main() {
    signal<void(char*)> s;
    Some some;
    Some other;
    s.connect(some);
    s.connect(bind(&Some::Update, other, _1));
    s.connect(func);
    char str[10] = "some str";
    s(str);
    return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top