How can I call non-existent functions in C++ - c++

So, I want to know how I can call functions from header...
To explain it better, I have a header file, which is something similar to a game library.
I want to call certain functions in the Main part of the program(the dynamic one), but I want these functions not to be required.
So, if I click a hotkey combo, I'd call a function in Main part of the program called "hotkeyHit", but first I need to check if it's there. I'm implementing some kind of an "Event system".
And that's where I hit the wall...
First of all I don't know how to check if there is that function in the Main, I can't compile if there is no function called that and last of all, I can't declare the same function for second time, which leaves me with no obvious options.
So now I'd like to know how I can do that so it would work the way I want it to.
Thanks in advance

Some example clode below to hopefully explain my comment. In this, the methods in the CBaseHandler class are intentionally empty. Your Event Handler takes a reference to a CBaseHandler and in this example tries to handle a keypress and a mouseclick. However, the concrete implementation of the handler, CHandler only implements the Keypress handler (in this case just by printing a string, but you can do whatever you want)
When the Event Handler runs, only the Keypress will do anything. Presumably you'll be wanting to call that in a loop of some description in real life.
The event handler loop in your library can now take any implementation of an event handler for whatever purposes you need.
#include <iostream>
class CBaseHandler
{
public:
virtual void handleKeyPress(int i)
{
}
virtual void handleMouseClick(int i)
{
}
};
class CHandler : public CBaseHandler
{
public:
virtual void handleKeyPress(int i)
{
std::cout << "Derived - KP" << std::endl;
}
};
void DoHandle(CBaseHandler& handler)
{
handler.handleKeyPress(4);
handler.handleMouseClick(0);
}
int main() {
CHandler myhandler;
DoHandle(myhandler);
}

If you have a function declared in header file but not defined anywhere, this will compile fine. However if you attempt to use this function anywhere in the code, the linker will complain when you try to compile it as it won't be able to find the definition. So you could simply add dummy definition which does nothing.
header.h
void myFunction();
source.cpp (1)
int main()
{
myFunction(); // linker error on compile
return 0;
}
source.cpp (2)
void myFunction() {}; // dummy definition
int main()
{
myFunction(); // no problem
return 0;
}

Ok, so after getting some help from you guys and figuring it out online, I've found a solution that works for me.
I've set it up like so:
Main code:
void mouseClicked();
void main(){
setMouseClicked(mouseClicked);
}
void mouseClicked();
Header code:
void (*mc)() = NULL;
void setMouseClicked(void (*fun)(void)){
mc = fun;
}
and then in the event function I do this:
void handleMousePress(int button, int state, int x, int y){
mouseX = x;
mouseY = y;
mouseButton = button;
if(state == GLUT_DOWN){
if(mc != NULL)
(*mc)();
}
}
I've worked on a compromise by having a declaration of the function in the main part of the code and having a setter for that function, but with that I've added an ability for renaming functions that are called when the event is triggered.
So once again, thanks for your suggestions, but at the end I've found that pointers to functions work the best.

Related

C++/Omnet++ Function is ignored in VeinsInetSampleApplication, veins_inet

I don't know whether I don't get the logic behind adding a function to eclipse/omnet++:
Tried to simply add a new function "init_func" to the VeinsInetSampleApplication.h Header file
#pragma once
#include "veins_inet.h"
#include "VeinsInetApplicationBase.h"
class VEINS_INET_API VeinsInetSampleApplication : public veins::VeinsInetApplicationBase {
protected:
bool haveForwarded = false;
protected:
virtual bool startApplication() override;
virtual bool stopApplication() override;
virtual void processPacket(std::shared_ptr<inet::Packet> pk) override;
// ADAPTION 2022/05/28
virtual void init_func();
public:
VeinsInetSampleApplication();
~VeinsInetSampleApplication();
};
However when I simply copy the initialization code of the startApplication() function into "init_func()" in VeinsInetSampleApplication.cc "init_func()" is simply ignored by my simulation.
Here's the code snippet which basically shall send a message to all my simulation nodes at time t=5 sec. The only difference to the startApplication() function is that the message sending is triggered at t=5sec. and not at t=10sec.
The startApplication() function does its job correctly and even if i comment it out and only make my init_func() function run it is also ignored. (I tried this in order to rule out any issues with the "this" pointer etc. which would suggest there is a "bad interaction" between both functions). So it really seems like my init_func() is not registered. But I don't know. Does anybody have an idea why "init_func()" might be ignored here by Omnet++?
Code of init_func():
void VeinsInetSampleApplication::init_func()
{
// host[0] should stop at t=5s, change in timerManger.create(...)
if (getParentModule()->getIndex() == 0) {
auto callback = [this]() {
getParentModule()->getDisplayString().setTagArg("i", 1, "red");
traciVehicle->setSpeed(0);
auto payload = makeShared<VeinsInetSampleMessage>();
timestampPayload(payload);
payload->setChunkLength(B(100));
payload->setRoadId(traciVehicle->getRoadId().c_str());
auto packet = createPacket("accident");
packet->insertAtBack(payload);
sendPacket(std::move(packet));
};
timerManager.create(veins::TimerSpecification(callback).oneshotAt(SimTime(5, SIMTIME_S)));
}
}
(I also changed return type of "init_func" to bool to further increase similarity. But that of course was also not successful)
Best regards,
Lukas
init_func() is ignored because it is not called neither by initialize() nor by any other method. You decided to create a new method, so you have to add calling of that method somewhere in the code.

C++ Namespace around header declaration and source definition

I am making a static library, everything defined in it is all in one namespace. But I am unsure whether I should define the methods as if you would a class, or also wrap them in the namespace. What I'm asking is:
Is this valid:
MyThings.h
namespace MyThings {
void DoStuff();
void DoOtherStuff();
}
MyThings.cpp
namespace MyThings {
void DoStuff() {
// Do this.
}
void DoOtherStuff() {
// Do that.
}
}
Or, should I define it like I would class methods?:
MyThings.cpp
void MyThings::DoStuff() {
// Do this.
}
void MyThings::DoOtherStuff() {
// Do that.
}
I would prefer not to use using namespace MyThings;, and I would prefer to use my first example if it is valid, I feel it makes the code more readable without having to use MyThings:: before every method identifier.
Both are valid, so you can pick your style according to taste.
There is an advertised advantage of defining the function using:
void MyThings::DoStuff() {
// Do this.
}
which is that in order to do it, the function must have already been declared. Thus, errors like:
void MyThings::DoStuf() {
// Do this.
}
or
void MyThings::DoStuff(int i) {
// Do this.
}
are caught when you compile MyThings.cpp. If you define
namespace MyThings {
void DoStuff(int i) {
// Do this.
}
}
then you generally won't get an error until someone in another source file tries to call the function, and the linker complains. Obviously if your testing is non-rubbish you'll catch the error one way or another, but sooner is often better and you might get a better error message out of the compiler than the linker.

C++ beginner's coding mistake: "Undeclared identifier"?

I'm to use C++ for a very small part of my project. I must be coding something wrong, but my knowledge of C++ is what it is and I can't get around this...
See both the AbstractContactListener.h and .mm files below. The problem is in isFixtureCollidingWithFixtureOfType(...) method, I can't access the _contact vector. What could I be doing wrong here?
header:
struct JRContact {
b2Fixture *fixtureA;
b2Fixture *fixtureB;
bool operator==(const JRContact& other) const
{
return (fixtureA == other.fixtureA) && (fixtureB == other.fixtureB);
}
};
class AbstractContactListener : public b2ContactListener {
id contactHandler;
public:
std::vector<JRContact>_contacts;
AbstractContactListener(id handler);
~AbstractContactListener();
void isFixtureCollidingWithFixtureOfType(b2Fixture fix, int type);
virtual void BeginContact(b2Contact* contact);
virtual void EndContact(b2Contact* contact);
};
Implementation:
AbstractContactListener::AbstractContactListener(id handler) : _contacts() {
contactHandler = handler;
}
AbstractContactListener::~AbstractContactListener() {
}
void isFixtureCollidingWithFixtureOfType(b2Fixture fix, int type){
std::vector<JRContact>::iterator ct;
// Next line is faulty... can't call _contacts.begin()
// xCode says: "Use of undeclared identifier _contacts"
ct = _contacts.begin();
}
void AbstractContactListener::BeginContact(b2Contact* contact) {
// ...
}
void AbstractContactListener::EndContact(b2Contact* contact) {
// ...
}
Undeclared? Hmm. I thought I was declaring it in the header, right after the "public:" keyword.
What could I be doing wrong here?
thanks a lot!
J.
You forget to add the scope of the function. Try:
void AbstractContactListener::isFixtureCollidingWithFixtureOfType(b2Fixture fix, int type){
Why is the error pointing you to that strange place? The compiler sees your function definition and thinks that this is a free function, as there is nothing that indicates otherwise and tries to handle it as such. It fails, because it tries to find the variable in the global scope. This can get even funnier (read: more confusing): Image that this function does not use a class member. It will be simply parsed and compiled as a free function. As soon as your try to call it on an object of that type you will get a linker error.
Also, I cannot see a declaration of the type id which is used in AbstractContactListener but that might just be because the code sample is incomplete.
You forgot the class name from
void isFixtureCollidingWithFixtureOfType(b2Fixture fix, int type)
void AbstractContactListener::isFixtureCollidingWithFixtureOfType(b2Fixture fix, int type)
In the implementation.
:)

C++ - basic function question

Is there any way to make a function call only once?
Suppose I have some class
struct A {
void MainRoutine(Params) {
// Want to call other routine only once
}
void OtherRoutine(Params) {
// Do something that should be done only once and
// what depends on the params
}
};
I want to call OtherRoutine only once in MainRoutine (I assume that MainRoutine is going to be called N times. I can't call OtherRoutine from the constructor, because it accepts Params which may not be available at the time when object is being constructed.
Basically I want to do something like
static bool called = false;
if (!called) {
OtherRoutine(Params);
called = true;
}
but I hope there is a more "beautiful" way of doing this... (which could be written in one line)
Maybe something using boost::function or some part of boost that I don't know about? :)
Thank you
Take a look at Boost Thread's one-time initialization mechanism
You can also put the call-only-once logic, which you already outlined, inside OtherRoutine, causing it to return early if it has already been executed before.
Logically, its pretty much the same. Stylistically, it might be nicer.
You were definitely on the right track already. You should put your static 'called' variable inside your struct... ahem: you should make it a class instead, make it private, and make sure the state of the static variable is queried inside of OtherRoutine. You should not make it more complicated than it needs to be. Using boost, or anything else for so simple a mechanism is just overkill.
You could achieve this with boost::function and bind. Assuming you want OtherRoutine only to be called once per object,
struct A {
A() {
Routine = boost::bind(&A::OtherRoutine, this);
}
boost::function<void()> Routine;
private:
void MainRoutine() {
// Do stuff that should occur on every call
}
void OtherRoutine() {
Routine = boost::bind(&A::MainRoutine, this);
// Do stuff that should only occur once
MainRoutine();
}
};
A foo;
foo.Routine(); // OtherRoutine is called
foo.Routine(); // Now all subsequent calls will go to MainRoutine
foo.Routine();
I would suggest doing what the other people have said, though. While this may look 'cleaner,' it's overly complicated when compared to the alternatives.
Another way that verges on "cute" would be to have a static object and call your function from within its constructor. Something like...
struct OneShotOtherRoutine
{
OneShotOtherRoutine(A a, Params params)
{
a.OtherRoutine(params);
}
};
struct A
{
friend struct OneShotOtherRoutine;
public:
void MainRoutine(Params params)
{
static OneShotOtherRoutine(params);
// Main Routine code
}
private:
void OtherRoutine(Params params)
{
// Other routine code
}
};
You'd have to split things up so that each implementation could see the other struct's declaration, but this could do what you want, assuming it's acceptable that OtherRoutine gets called when statics are initialized.

Function Call Guard

Suppose I have a free function called InitFoo. I'd like to protect this function from being called multiple times by accident. Without much thought I wrote the following:
void InitFoo()
{
{
static bool flag = false;
if(flag) return;
flag = true;
}
//Actual code goes here.
}
This looks like a big wart, though. InitFoo does not need to preserve any other state information. Can someone suggest a way to accomplish the same goal without the ugliness?
Macros don't count, of course.
You can do it with some different ugliness:
struct InitFoo
{
InitFoo()
{
// one-time code goes here
}
};
void Foo()
{
static InitFoo i;
}
You're still using static, but now you don't need to do your own flag checking - static already puts in a flag and a check for it, so it only constructs i once.
Well, a constructor is only automatically called once. If you create a single instance of this class:
class Foo
{
public:
Foo(void)
{
// do stuff
}
}
Then //do stuff will only execute once. The only way to execute it twice is to create another instance of the class.
You can prevent this by using a Singleton. In effect, //do stuff can only possibly be called once.
I'd like to protect this function from being called multiple times by accident
To me, this sounds like an issue that will only come up during debugging. If that is the case, I would simply do the following:
void InitFoo()
{
#ifndef NDEBUG
static bool onlyCalledOnce = TRUE;
assert(onlyCalledOnce);
onlyCalledOnce = FALSE;
#endif
...
}
The purpose of this particular wart is easily discerned just by looking at it, and it will cause a nice, big, flashy assertion failure if a programmer ever makes the mistake of calling InitFoo more than once. It will also completely dissapear in production code. (when NDEBUG is defined).
edit: A quick note on motivation:
Calling an init function more than once is probably a big error. If the end user of this function has mistakenly called it twice, quietly ignoring that mistake is probably not the way to go. If you do not go the assert() route, I would recommend at least dumping a message out to stdout or stderr.
That is exactly how I'd do it. You could use some function pointer shuffling if you want an alternative:
static void InitFoo_impl()
{
// Do stuff.
// Next time InitFoo is called, call abort() instead.
InitFoo = &abort;
}
void (*InitFoo)() = &InitFoo_impl;
Do you also need it to be multi-thread safe? Look into the Singleton pattern with double-check locking (which is surprising easy to get wrong).
If you don't want a whole class for this, another simple way is:
In a .cpp (don't declare InitBlah in the .h)
// don't call this -- called by blahInited initialization
static bool InitBlah()
{
// init stuff here
return true;
}
bool blahInited = InitBlah();
No one can call it outside of this .cpp, and it gets called. Sure, someone could call it in this .cpp -- depends on how much you care that it's impossible vs. inconvenient and documented.
If you care about order or doing it at a specific time, then Singleton is probably for you.
I do exactly that all the time with situations that need that one-time-only-but-not-worth-making-a-whole-class-for. Of course, it assumes you don't worry about thread-related issues. I usually prefix the variable name with "s_" to make it clear that it's a static variable.
Hmmm... if you don't object to using Boost, then have a look at boost::call_once:
namespace { boost::once_flag foo_init_flag = BOOST_ONCE_INIT; }
void InitFoo() {
// do stuff here
}
void FooCaller() {
boost::call_once(&foo_init_flag, InitFoo);
// InitFoo has been called exactly once!
}
void AnotherFooCaller() {
boost::call_once(&foo_init_flag, InitFoo);
// InitFoo has been called exactly once!
}
Not that I am very excited about it, but this is just another way: function object.
#import <iostream>
class CallOnce {
private:
bool called;
public:
CallOnce() {
called = false;
}
void operator()(void) {
if (called) {
std::cout << "too many times, pal" <<std::endl;
return;
}
std::cout << "I was called!" << std::endl;
called = true;
}
};
int main(void) {
CallOnce call;
call();
call();
}