#include "dataConsumer.h"
#include <iostream>
#include <Windows.h>
DataConsumer::DataConsumer(){}
DataConsumer::~DataConsumer(){}
void DataConsumer::Body()
{
std::cout << "DataConsumer Start" << std::endl;
while (1)
{
//I want to get providerData_ of DataProvide class in here
Sleep(1000);
}
}
#include "dataProvider.h"
#include <iostream>
#include <Windows.h>
DataProvider::DataProvider(){}
DataProvider::~DataProvider(){}
void DataProvider::Body()
{
std::cout << "DataProvider Start" << std::endl;
while (1)
{
//Update data in here
providerData_++;
Sleep(1000);
}
}
There are two classes.
And I want to get providerData_ of dataProvider class in dataConsumer class.
To resolve this situation, I thought the following is one solution.
I made singleton dataTransfer class like below.
But I am not sure whether this is a general solution in c++.
First of all, I want to know whether my solution is available.
To the next, If you know the better solution(or design pattern) to resolve my situation, please advise to me.
#ifndef DATATRANSFER_H
#define DATATRANSFER_H
class DataTransfer
{
public:
static DataTransfer* getInstance()
{
static DataTransfer instance;
return &instance;
}
void GetData(unsigned int *data)
{
if(data)
*data = data_;
}
void SetData(unsigned int *data)
{
if(data)
data_ = *data;
}
private:
DataTransfer(){}
~DataTransfer(){}
unsigned int data_;
};
#endif
#include "dataConsumer.h"
#include "dataTransfer.h"
#include
#include
DataConsumer::DataConsumer(){}
DataConsumer::~DataConsumer(){}
void DataConsumer::Body()
{
unsigned int data = 0;
std::cout << "DataConsumer Start" << std::endl;
while (1)
{
//I want to get providerData_ of DataProvide class in here
DataTransfer::getInstance()->GetData(&data);
std::cout << "DataConsumer data:" << data << std::endl;
Sleep(1000);
}
}
#include "dataProvider.h"
#include "dataTransfer.h"
#include
#include
DataProvider::DataProvider() : providerData_(0)
{
}
DataProvider::~DataProvider(){}
void DataProvider::Body()
{
std::cout << "DataProvider Start" << std::endl;
while (1)
{
//Update data in here
providerData_++;
DataTransfer::getInstance()->SetData(&providerData_);
Sleep(1000);
}
}
If both classes need to be able to get and set the providerData_, I would create a third Data class to own the providerData_.
Then I could give a pointer of the Data class to all the classes that needed access to that data.
There are 3 patterns called aggregation, composition and association in software architecture.
The pattern in which class Foo can use class Bar but does not "own" it and both classes remain independent is Association.
DataConsumer have a pointer to DataProvider :
// Association
class DataConsumer{
private:
DataProvider* provider;
public:
void setProvider(DataProvider* p) { provider = p; }
void Body();
int /* or whatever data type */ getData()
{
if(provider != nullptr)
{
return provider->getData();
}
else
{
// handle provider not being set
return ...;
}
}
};
DataProvider must be allocated / created outside of DataConsumer and is independent.
Read this answer and this answer for a better explanation on these pattern.
Related
I am attempting to create a wrapper around class functions. The purpose of my wrapper is to test input, output, and enforce order of operations with various calls throughout my program. I am trying to not make any changes to the callee class. Attached is an example of what I am trying to achieve, but unable to figure out.
Main.cpp
#include "func_warpper.h"
#include "func.h"
int main()
{
func_wrapper fw
fun func;
int origValue = 5;
fw.caller([&](int origValue) { func.f(origValue); }, origValue);
int output = func.getResult().number;
std::cout << " value outputed by function 2 : " << output << std::endl;
// output
// note that above line does give me the result I am looking for
// however, I want to be able to get this inside the function of caller
return 0;
}
func.h .... I want this to be unmodified
#ifndef FUN_H
#define FUN_H
class fun
{
public:
struct result
{
int number;
};
fun();
~fun();
void f(int value);
struct result getResult(){return this->testResult;};
private:
struct result testResult;
};
#endif
func.cpp .... I want this to be unmodified
#include "func.h"
fun::fun(){
this->testResult.number = 0;
return;
}
fun::~fun(){
return;
}
void fun::f(int value){
int updateValue = value * 5;
this->testResult.number = updateValue;
}
func_wrapper.h .... I can modify this until the cows come home, please go ham with recommended changes :)
class func_wrapper
{
public:
struct new_result
{
int new_number;
};
func_wrapper();
~func_wrapper();
void caller(std::function<void(int)> clb, int val);
struct new_result getNewResult() { return this->new_testResult; };
private:
struct new_result new_testResult;
};
#endif
func_wrapper.cpp .... same as above, I can modify this until the cows come home, please go ham with recommended changes :)
#include "func_wrapper.h"
func_wrapper::func_wrapper()
{
//ctor
this->new_testResult.new_number = 0;
return;
}
func_wrapper::~func_wrapper()
{
//dtor
}
void func_wrapper::caller(std::function<void(int)> clb, int val)
{
std::cout << " value entered into function: " << val << std::endl;
// clb(val); seems to call the function but does not store locally anything
clb(val);
clb;
// clb; seems to store all the information locally however I seem unable to
// to reach the infromation: clb -> [functor] -> func -> testResult -> number
// would like ...
int output = clb ??? // the result of what gets filled from number struct
// if I attempt to #include func.h
// func func;
// func.getResult().number; locally the answer is zero with or without delay
}
Through several days of searching, I have not found anything that can help with this problem, to include similar enough questions on stack overflow. Any help would be greatly appreciated, thank you.
So, my understanding is that inside func_wrapper::caller you want to be able to access the wrapped class that is inside your callback. Unfortuately, the way you are doing it, is impossible. There is no (legitimate) way to reach inside the function and access its arguments.
However, if you break up the operation into its component parts, you can do what you want. You would want a caller function more like this:
template <typename Type, typename Function>
void caller(Type&& functor, Function function, int val)
{
std::cout << " value entered into function: " << val << std::endl;
std::invoke(function, functor, val);
std::cout << "value inside wrapper: " << functor.getResult().number << "\rn";
}
and then call it like this.
fw.caller(func, &fun::f, origValue);
https://godbolt.org/z/151YfEeoo
#JohnFilleau had mentioned to pass the class object instead of the function from within the class. The following is the solution based on example code that he provided, and I modified to work with the example. I realize the question is confusing but would like to thank both JohnFilleau and Taekahn for the discussion.
In main.cpp
int main()
{
func_wrapper fw;
fun func;
int origValue = 5;
fw.caller2(func, origValue);
return 0:
}
func_wrapper::caller2
void func_wrapper::caller2(fun& fun, int val)
{
std::cout << " value entered into function: " << val << std::endl;
fun.f(val);
int output = fun.getResult().number;
std::cout << " did this work: " << output << std::endl;
}
In the header I had to add
#include "func.h"
with the change to the header as follows
void caller2(fun& fun, int val);
I've been recently doing a lot of reading and decided to try and implement a simple State pattern to try and see how things fit together.
However, I've ran into an issue I've never come across before: The Scene's subclass (Start) doesn't seem to inherit the value of a pointer set by the superclass' constructor.
Here's the code
//main.cpp
#include "Game/game.hpp"
#include "Game/Scene/start.hpp"
int main()
{
Game::Game *g = new Game::Game;
Game::Scene::Start *s = new Game::Scene::Start(g);
g->set_scene(s);
g->loop();
delete g;
return 0;
}
//Game/Scene/Scene.hpp
#ifndef GAME_SCENE_H
#define GAME_SCENE_H
namespace Game
{
class Game;
namespace Scene
{
class Scene
{
public:
Scene(Game *game);
virtual ~Scene();
virtual void handle_input() = 0;
virtual void update();
protected:
Game *game;
};
}
}
#endif
//Game/Scene/Scene.cpp
#include "scene.hpp"
#include <iostream>
Game::Scene::Scene::Scene(Game *game): game(game)
{
std::cout << "Game::Scene::Scene::Scene() > game: " << this->game << std::endl;
}
Game::Scene::Scene::~Scene() {}
void Game::Scene::Scene::update()
{
std::cout << "Game::Scene::Scene::update(): game: " << game << std::endl;
}
//Game/Scene/start.hpp
#ifndef GAME_SCENE_START_H
#define GAME_SCENE_START_H
#include "scene.hpp"
namespace Game
{
namespace Scene
{
class Start:
public Scene
{
public:
Start(Game *game);
void handle_input() override;
void update() override;
protected:
Game *game;
};
}
}
#endif
//Game/Scene/start.cpp
#include "start.hpp"
#include "../game.hpp"
#include <iostream>
Game::Scene::Start::Start(Game *game): Scene(game) {
std::cout << "Game::Scene::Start::Start() > game: " << this->game << std::endl;
}
void Game::Scene::Start::handle_input()
{}
void Game::Scene::Start::update()
{
Scene::update();
std::cout << "Game::Scene::Start::update(): game: " << game << std::endl;
game->set_keep_going(false);
}
//Game/game.hpp
#ifndef GAME_H
#define GAME_H
#include "Scene/scene.hpp"
namespace Game
{
class Game
{
public:
Game();
void loop();
void set_keep_going(bool state);
void set_scene(Scene::Scene *scene);
private:
bool keep_going;
Scene::Scene *current_scene;
};
}
#endif
//Game/game.cpp
#include "game.hpp"
#include <iostream>
Game::Game::Game():
keep_going(true),
current_scene(nullptr)
{}
void Game::Game::loop()
{
while(keep_going && current_scene)
{
current_scene->handle_input();
current_scene->update();
}
return;
}
void Game::Game::set_keep_going(bool state)
{
keep_going = state;
}
void Game::Game::set_scene(Scene::Scene *scene)
{
if(scene)
{
if(current_scene)
{
delete current_scene;
}
current_scene = scene;
}
}
And here is the output it generates:
Game::Scene::Scene::Scene() > game: 00000210FA38B330
Game::Scene::Start::Start() > game: 0000000000000000
Game::Scene::Scene::update(): game: 00000210FA38B330
Game::Scene::Start::update(): game: 0000000000000000
Segmentation fault
If I remove the 'this->' part that I used in the subclass constructor for debugging the output becomes this
Game::Scene::Scene::Scene() > game: 000001D247B5B370
Game::Scene::Start::Start() > game: 000001D247B5B370
Game::Scene::Scene::update(): game: 000001D247B5B370
Game::Scene::Start::update(): game: 0000000000000000
Segmentation fault
Which just makes it even weirder to me that it suddenly decided to reset itself.
It's without a doubt an incredibly simple thing that I'm overlooking, or some pointer shennanigans I've never run into before, but I'm stumped on what can possibly be going on here.
Any help or feedback om my code would be appriciated.
You have two members variables Scene::game and Start::game. You never set Start::game. By default, game resolves to Scene::game and the base class's variable is shadowed. Turn on compiler warnings, maybe the compiler will warn about it, not sure in this particular case.
Fix:
Game::Scene::Start::Start(Game *game): Scene(game), game(game)
{
std::cout << "Game::Scene::Start::Start() > game: " << this->game << std::endl;
}
Or just delete Start::game and use the member from Scene. This probably what you have meant in the first place hence the protected qualifier.
If you want feedback - do not use new, use std::unique_ptr instead. Even better, do not use ptrs at all this is not Java.
y'all I'm having an issue trying to access the member functions of an object that I have stored in an array of pointers full of objects.
Header:
#ifndef COURSEGRADES__H
#define COURSEGRADES__H
#include "Essay.h"
#include "FinalExam.h"
#include "PassFailExam.h"
#include "GradedActivity.h"
class CourseGrades:public Essay, public FinalExam, public PassFailExam, public GradedActivity
{
public:
CourseGrades();
void setLab(GradedActivity &l);
void setPassFailExam(PassFailExam &pf);
void setEssay(Essay &e);
void setPassFailFinal(FinalExam &fe);
void print();
private:
GradedActivity *grades[4];
};
#endif // COURSEGRADES_H
CPP
#include "CourseGrades.h"
#include <iostream>
CourseGrades::CourseGrades()
{
//ctor
}
void CourseGrades::setLab(GradedActivity &l)
{
grades[0] = &l;
}
void CourseGrades::setPassFailExam(PassFailExam &pf)
{
grades[1] = &pf;
}
void CourseGrades::setEssay(Essay &e)
{
grades[2] = &e;
}
void CourseGrades::setPassFailFinal(FinalExam &fe)
{
grades[3] = &fe;
}
void CourseGrades::print()
{
std::cout << grades[0]->getScore() << "\t" << grades[0]->getLetterGrade() << std::endl;
std::cout << grades[1]->getScore() << "\t" << grades[1]->getLetterGrade() << std::endl;
std::cout << grades[2]->getScore //this function exists in the Essay class but I can't access it from here.
}
So I'm trying to access the third object in the grade array which is an object of the essay class which includes a unique function that is separate from the get score function in the GradeActivity class. I'll also need to access its unique getLetterGrade method but once I get one I should be able to find out how to get the other. Any help would be greatly appreciated.
Does std::future in c++ support polymorphism?
So, if to store child_class in future<parent_class>, can I after get it after by dynamic_cast<child_class>?
Providing you use a reference or a pointer (probably obvious since it'll fail to compile otherwise)... Yes.
#include <iostream>
#include <future>
using namespace std;
struct Parent {
virtual void a() { cout << "I am parent"; }
};
struct Child : Parent {
virtual void a() { cout << "I am child"; }
};
Child g_c; //just some global for the purposes of the example
int main() {
std::future<Parent&> p = async(launch::async, []() -> Parent& { return g_c; });
auto c = dynamic_cast<Child&>(p.get());
c.a();
return 0;
}
code result here: http://ideone.com/4Qmjvc
Before I present the code which is found at the bottom of this post I would like to talk about the issue and the fix's that I do not desire. Okay basically I've created a GUI from scratch sort of and one requirement I wanted for this was allow components to have their own click executions so if i click a button or tab etc.. It would call Component->Execute(); Well normally you would do something like a switch statement of ids and if that components ID equaled n number then it would perform this action. Well that seemed kinda dumb to me and I thought there has to be a better way. I eventually tried to incorporate a feature in JAVA where you would do like Component.AddActionListener(new ActionListener( public void execute(ActionEvent ae) { })); or something like that and I thought that this feature has to be possible in C++. I eventually came across storing void functions into a variable in which could be executed at any time and modified at any time. However I hadn't noticed an issue and that was this only worked with static functions. So below you'll see my problem. I've patched the problem by using a pointer to SomeClass however this would mean having an individual function call for every class type is there no way to store a function callback to a non-static class member without doing the below strategy? and instead doing a strategy like the commented out code?
//Main.cpp
#include <iostream> //system requires this.
#include "SomeClass.h"
void DoSomething1(void)
{
std::cout << "We Called Static DoSomething1\n";
}
void DoSomething2(void)
{
std::cout << "We Called Static DoSomething2\n";
}
int main()
{
void (*function_call2)(SomeClass*);
void (*function_call)() = DoSomething1; //This works No Problems!
function_call(); //Will Call the DoSomething1(void);
function_call = DoSomething2; //This works No Problems!
function_call(); //Will Call the DoSomething2(void);
SomeClass *some = new SomeClass(); //Create a SomeClass pointer;
function_call = SomeClass::DoSomething3; //Static SomeClass::DoSomething3();
function_call(); //Will Call the SomeClass::DoSomething3(void);
//function_call = some->DoSomething4; //Non-Static SomeClass::DoSomething4 gives an error.
//function_call(); //Not used because of error above.
function_call2 = SomeClass::DoSomething5; //Store the SomeClass::DoSomething(SomeClass* some);
function_call2(some); //Call out SomeClass::DoSomething5 which calls on SomeClass::DoSomething4's non static member.
system("pause");
return 0;
}
//SomeClass.hpp
#pragma once
#include <iostream>
class SomeClass
{
public:
SomeClass();
~SomeClass();
public:
static void DoSomething3(void);
void DoSomething4(void);
static void DoSomething5(SomeClass* some);
};
//SomeClass.cpp
#include "SomeClass.h"
SomeClass::SomeClass(void)
{
}
SomeClass::~SomeClass(void)
{
}
void SomeClass::DoSomething3(void)
{
std::cout << "We Called Static DoSomething3\n";
}
void SomeClass::DoSomething4(void)
{
std::cout << "We Called Non-Static DoSomething4\n";
}
void SomeClass::DoSomething5(SomeClass *some)
{
some->DoSomething4();
}
Secondary Fix for what I'll do not an exact answer I wanted but it meets my needs for now along with allowing additional features which would have become overly complicate had this not existed.
//Component.hpp
#pragma once
#include <iostream>
#include <windows.h>
#include <d3dx9.h>
#include <d3d9.h>
#include "Constants.hpp"
#include "ScreenState.hpp"
#include "ComponentType.hpp"
using namespace std;
class Component
{
static void EMPTY(void) { }
static void EMPTY(int i) { }
public:
Component(void)
{
callback = EMPTY;
callback2 = EMPTY;
callback_id = -1;
}
Component* SetFunction(void (*callback)())
{
this->callback = callback;
return this;
}
Component* SetFunction(void (*callback2)(int), int id)
{
this->callback_id = id;
this->callback2 = callback2;
return this;
}
void execute(void)
{
callback();
callback2(callback_id);
}
}
The syntax for pointers-to-member-functions is as follows:
struct Foo
{
void bar(int, int);
void zip(int, int);
};
Foo x;
void (Foo::*p)(int, int) = &Foo::bar; // pointer
(x.*p)(1, 2); // invocation
p = &Foo::zip;
(x.*p)(3, 4); // invocation
Mind the additional parentheses in the function invocation, which is needed to get the correct operator precedence. The member-dereference operator is .* (and there's also ->* from an instance pointer).