How do I call local function from a static function? - c++

#ifndef DATACENTER_H_
#define DATACENTER_H_
#include <map>
#include <list>
#include <string>
#include "LiLo/SoundInfo.h"
#include "MutexCondition.h"
#include "UserInfo.h"
using namespace std;
class DataCenter : MutexCondition{
private:
map<long long, list<SoundInfo *> > m_soundListMap;
void add(long long deviceId, SoundInfo* soundInfo);
public:
DataCenter();
virtual ~DataCenter();
static void addSoundInfo(long long deviceId, SoundInfo *soundInfo);
};
#endif /* DATACENTER_H_ */
DataCenter.cpp file
#include "DataCenter.h"
DataCenter::DataCenter() {
// TODO Auto-generated constructor stub
}
DataCenter::~DataCenter() {
// TODO Auto-generated destructor stub
}
void DataCenter::addSoundInfo(long long deviceId, SoundInfo *soundInfo){
add(deviceId, soundInfo);
}
void DataCenter::add(long long deviceId, SoundInfo *soundInfo){
list<SoundInfo*>& info_list = m_soundListMap[55];
}
I am trying to access the function call addSoundInfo from other classes so I have set this as static. Since the m_soundListMap is not a static so I think I need another function to access to the local data structure.
Inside of the static function, I call add function to add SoundInfo to the list. However, I am getting an error in the static function and it says "Can not call member function .... without object".
How do I fix this problem? Thanks in advance..

If you want to access addSoundInfo from other classes, you need to make it public, or make those other classes friends of DataCenter. static has nothing to with access control.
A static function is not bound to an instance of the class it belongs to, and thus can not access members of that class (it also can not call member-functions). If you really want to access members from a static function, you have to pass an instance of the class as argument the the static function explicitly.
If you struggle with such basic concepts, you should read a good book.

I suppose you mean you don't want to make void add() public and still you want to access it from some classes. It is nothing wrong with that and you can do it this way:
class A
{
private:
void DoPrivateStuf() {}
friend class B; // now B can access A private stuf
};
class B
{
// can have any modifier: public, private, protected depending on your needs
public:
void DoPrivateStufToA( A& a )
{
a.DoPrivateStuf();
}
};

The code seems hopelessly jumbled, but technically you just need to remove the word static. Then you can call dc.addSoundInfo( id, pSoundInfo ) where dc is a DataCenter object.
Cheers & hth.,

static is a way to instruct the compiler "the following function is not manipulating instance variable, only things that are global to all the instances of this class". You use that when you need to keep your constructor private for some reason, or have a function that does instances management (registration, etc.)
When you intend to have only one instance of a given class (e.g. because it is a resource manager), you usually prefer to follow the singleton pattern: a static getInstance() method that return the only instance of that class and create it if needed, then you keep your other methods regular methods and your state instance members.

As others have said, making addSoundInfo() public is enough for it to be available from other class. I'll just add some points about C++'s keyword static. Basically, it has many meanings depending on where is it used. When one uses it for functions, there are two meanings:
static class function: a function that is tied to a class, not any specific object. In this sense, it is similar to namespace concept - using the scope :: operator to access the function.
static function: The function has internal linkage, which means it is only visible in current translation unit (current source file). It is handy for utility functions.
In your case, the answer to your question will technically be something like this:
In the header file:
class DataCenter
{
static void addSoundInfo(DataCenter& dc, long long deviceId, SoundInfo *soundInfo);
}
In the source file:
void DataCenter::addSoundInfo(DataCenter& dc, long long deviceId, SoundInfo *soundInfo)
{
dc.add(deviceId, soundInfo);
}
But it is probably not what you want.

Related

Accessing a variable from an unrelated function in C++

I want to access a variable of one class into another class, and set it to some value, e.g. like in code here, i wanna set the some_flag to true in the secondClassFunction(). Is it possible? If yes, how to do it?
Constraints due to system architecture:
The two classes are not inheritable.
The two classes are not related either.
The function signatures of secondClassFunction()cannot be changed.
Here's the code snippet:-
#include <iostream>
using namespace std;
class FirstClass{
bool some_flag;
public:
void setFlag(bool flag);
bool getFlag();
};
FirstClass::FirstClass(){
some_flag(false);
}
class SecondClass{
public:
void secondClassFunction();
}
SecondClass::secondClassFunction(){
// do something here.
// I want to access some_flag using SecondClass object.
// how to do this?
}
int main() {
SecondClass secObj;
secObj.secondClassFunction();
return 0;
}
Will wrapper classes help? If yes, how?
EDIT:-
Constraint 4. Cannot make the classes friend functions.
Constraint 5. Cannot globalize the flag variable.
Details:-
The flag is set in a function which is a member of FirstClass.
I wish to reset this flag in a function which is member of the SecondClass.
The two classes are not related, inheritable, and their access specifiers cannot be changed, due to constraints of the system architecture.
The flag is like a semaphore, it's used by multiple tasks, to denote the status of an activity, such as, whether the processor has received a certain command from a mobile app or not.
It seems that you do not care about instance of the FirstClass. So the following approach will work for you:
void SecondClass::secondClassFunction()
{
// Create local instance of the object to change
FirstClass first;
first.setFlag(true);
}
But it makes no sense at all. You need to know which object to modify. I'd suggest three options:
make instance of FirstClass static, global or singleton and modify it
make some_flag and its setter static
set instance of the FirstClass to context before calling SecondClass::secondClassFunction()
Third option explained:
class FirstClass; // Forward declaration
class SecondClass
{
...
FirstClass* firstClassInstance;
...
void setFirstClassInstanceToModify(FirstClass* first)
{
firstClassInstance = first;
}
...
};
void SecondClass::secondClassFunction()
{
firstClassInstance->setFlag(true);
}
And call it like this
FirstClass first;
...
SecondClass second;
...
second.setFirstClassInstanceToModify(&first);
second.secondClassFunction();
But make sure to have proper and valid instance before calling secondClassFunction

Hiding members in public interface and ODR

I have multiple classes in a library that have internals that I wish to hide from client code. From the client's perspective, each class is queried from a library class and is only used as an opaque pointer. An example is as follows:
struct SomeSystem;
void doSomethingToSomeSystem(SomeSystem* system, Parameters params);
void doSomethingElseToSomeSystem(SomeSystem* system, Parameters params);
On the implementation side, SomeSystem has multiple members which are not visible to the caller. This is all fine but I don't really like the clunky usage syntax:
SomeSystem* system = lib->getSomeSystem();
doSomethingToSomeSystem(system, params);
doSomethingElseToSomeSystem(system, params);
Another approach is this:
struct SomeSystem;
namespace somesystem {
void doSomething(SomeSystem* system, Parameters params);
void doSomethingElse(SomeSystem* system, Parameters params);
}
With the usage code:
SomeSystem* system = lib->getSomeSystem();
somesystem::doSomething(system, params);
somesystem::doSomethingElse(system, params);
I could also use global methods called doSomething and doSomethingElse and depend on function overloading if another type also defines doSomething. However, in this case, it is hard to find all "members" of SomeSystem in an IDE.
I am tempted to actually use member functions:
struct SomeSystem {
void doSomething(Parameters params);
void doSomethingElse(Parameters params);
};
With the usage code:
SomeSystem* system = lib->getSomeSystem();
system->doSomething(params);
system->doSomethingElse(params);
The last snippet looks good to me but SomeSystem is no longer an opaque pointer - it actually defines members. I'm a bit wary of this. One potential problem is the one definition rule. However, the "public" definition and "private" definition of the class will only be visible to different translation units. Is there any other badness hidden here? If the client code tries to instantiate SomeSystem on the stack or using new it would obviously crash the program. But I'm willing to accept that. Perhaps I can get around this by providing a private constructor in the public interface.
Another approach is of course to define an abstract class with pure virtual methods. However, I would like to avoid the overhead of this in case it is not absolutely necessary.
EDIT:
To be clear I am wondering if it is legal to have a public header that the client includes containing a different definition of the class (with some members missing) than what the implementation uses, as the client never instantiates the class.
Public header:
struct SomeSystem {
void doSomething(Parameters params);
void doSomethingElse(Parameters params);
};
Private header:
struct SomeSystem {
Member member;
void doSomething(Parameters params);
void doSomethingElse(Parameters params);
};
Private source (includes private header):
void SomeSystem::doSomething(Parameters params) {
...
}
void SomeSystem::doSomethingElse(Parameters params) {
...
}
This works when I test it but I am unsure if it violates the standard somehow. The two headers are never included in the same translation unit.
The PIMPL idiom is probably ideal in this situation, but it is an extra indirection on every access so there is that.
An alternative if you're just after some syntactic sugar might be to take advantage of ADL - it'll at least keep the system name out of the function name:
// publicly shared header file
namespace one_system
{
struct system;
typedef system* system_handle;
void do_something(system_handle );
};
// private implementation
namespace one_system
{
struct system {};
void do_something( system_handle ) { cout << "one"; }
};
int main() {
auto handle = /* SOMETHING TO GET THIS SYSTEM */;
do_something(handle); //do_something found by ADL
return 0;
}
EDIT:
I still think PIMPL is ideal. You also don't necessarily need to have an allocation nor any additional overhead compared to what you have already.
In the case where you have a system* and a function declaration (as per your examples), the compiler already has to do an indirection. You'll need a jump to that function (as it is defined in another translation unit) and indirections to access the system within the function (since it is taken as a pointer).
All you really need to do is define an interface for the class like so:
// put this in a namespace or name it according to the system
class interface
{
system_handle m_system;
public:
interface( system_handle s ) : m_system( s ) {}
interface() = delete;
void do_something();
};
Now in another translation unit, do_something() is defined to perform it's operation on the system. The lib->GetSystem() could return an instance of the interface. The interface can be fully declared in the header file since it only consists of the public functions. The system is still entirely private (in that the user of the lib won't have the header file declaring it's contents).
Furthermore the interface can be trivially copied around by the user. It doesn't care where it's pointer comes from so the library could pass in the address of a static if it wants.
The one downside I can see to this would be that member variables would need to have accessors (and there are many who would argue that every member variable should be private and have public or protected accessors anyway).
Another would be that the *this for interface would be passed into do_something and is probably not needed. This could be solved by having do_something defined in the header file too:
void do_something() { do_something_to_system( m_system ); }
Now the compiler should be able to optimize even the *this out since do_something can be inlined and the compiler could easily just insert code to load m_system into a register and call do_something_to_system (which would be similar to what you've mentioned in your examples).

Inherit Without Virtual Destructor

I have two classes that are used in a project. One class, Callback, is in charge of holding information from a callback. Another class, UserInfo, is the information that is exposed to the user. Basically, UserInfo was supposed to be a very thin wrapper that reads Callback data and gives it to the user, while also providing some extra stuff.
struct Callback {
int i;
float f;
};
struct UserInfo {
int i;
float f;
std::string thekicker;
void print();
UserInfo& operator=(const Callback&);
};
The problem is that adding members to Callback requires identical changes in UserInfo, as well as updating operator= and similarly dependent member functions. In order to keep them in sync automatically, I want to do this instead:
struct Callback {
int i;
float f;
};
struct UserInfo : Callback{
std::string thekicker;
void print();
UserInfo& operator=(const Callback&);
};
Now UserInfo is guaranteed to have all of the same data members as Callback. The kicker is, in fact, the data member thekicker. There are no virtual destructors declared in Callback, and I believe the other coders want it to stay that way (they feel strongly against the performance penalty for virtual destructors). However, thekicker will be leaked if a UserInfo type is destroyed through a Callback*. It should be noted that it is not intended for UserInfo to ever be used through a Callback* interface, hence why these classes were separate in the first place. On the other hand, having to alter three or more pieces of code in identical ways just to modify one structure feels inelegant and error-prone.
Question: Is there any way to allow UserInfo to inherit Callback publicly (users have to be able to access all of the same information) but disallow assigning a Callback reference to a UserInfo specifically because of the lack of virtual destructor? I suspect this is not possible since it is a fundamental purpose for inheritance in the first place. My second question, is there a way to keep these two classes in sync with each other via some other method? I wanted to make Callback a member of UserInfo instead of a parent class, but I want data members to be directly read with user.i instead of user.call.i.
I think I'm asking for the impossible, but I am constantly surprised at the witchcraft of stackoverflow answers, so I thought I'd ask just to see if there actually was a remedy for this.
You could always enforce the 'can't delete via base class pointer' constraint that you mentioned (to some extent) by making the destructor protected in the base class:
i.e.
// Not deletable unless a derived class or friend is calling the dtor.
struct Callback {
int i;
float f;
protected:
~Callback() {}
};
// can delete objects of this type:
struct SimpleCallback : public Callback {};
struct UserInfo : public Callback {
std::string thekicker;
// ...
};
As others have mentioned, you can delete the assignment operator. For pre-c++11, just make an unimplemented prototype of that function private:
private:
UserInfo& operator=(const Callback&);
struct UserInfo : Callback {
...
// assignment from Callback disallowed
UserInfo& operator=(const Callback&) = delete;
...
};
Note that the STL features a lot of inheritance without a virtual destructor. The documentation explicitly states that these classes are not designed to be used as base classes.
some examples are vector<>, set<>, map<> ....
Another approach is to consider private inheritance while providing an accessor method to reveal the Callback (in which case you may as well use encapsulation which is cleaner).
Yes, there's trickery you can use to keep the members in sync and update operator= automatically. It's ugly though, involving macros and an unusual way of using an include file.
CallBackMembers.h:
MEMBER(int, i)
MEMBER(float, f)
Elsewhere:
struct Callback {
#define MEMBER(TYPE,NAME) TYPE NAME;
#include "CallbackMembers.h"
#undef MEMBER
};
struct UserInfo {
#define MEMBER(TYPE,NAME) TYPE NAME;
#include "CallbackMembers.h"
#undef MEMBER
std::string thekicker;
void print(); // you can use the macro trick here too
UserInfo& operator=(const Callback& rhs)
{
#define MEMBER(TYPE,NAME) NAME = rhs.NAME;
#include "CallbackMembers.h"
#undef MEMBER
return *this;
}
};
There is no way to meet ALL the criteria you want.
Personally I think your idea to make it a member and then use user.call.i is the best and most clear option. Keep in mind that you write code that uses this just once, but you make up for it in maintainability (since your UserData never has to change) and readability (since it's 100% transparent to the end-use which attribute are part of the callback data and which are auxiliary).
The only other option that might make sense is to use private inheritance instead, and using the attribute or function into UserData. With this you still have to add one using when new data is added to callback, but you get your desired user.i syntax for clients.

C++ Get class type inside static function

Inside of a static member function I need to get the type.
class MyClass
{
public:
static void myStaticFunc();
...
};
And then in the implementation I want to have:
void MyClass::myStaticFunc()
{
// Get MyClass as a type so I can cast using it
(get_type_from_static_function()*)someOtherVariable;
}
Is this even possible? Normally I would use something from typeinfo on an object but I don't have this to work with.
I do not want to just use (MyClass*) because this is going inside of a macro and I'd like to keep it as simple as possible so that it can be called without a class name.
If it helps I am using QT but I couldn't find any macros to get the current class. It doesn't necessarily need to be programmatic - it can be a macro.
Cheers!
EDIT:
Here is the actual macro function:
#define RPC_FUNCTION(funcName) \
static void rpc_##funcName(void* oOwner, RpcManager::RpcParamsContainer params){ ((__class__*)oOwner)->funcName(params); }; \
void funcName(RpcManager::RpcParamsContainer params);
I then call RPC_FUNCTION(foo) in a class declaration. I want __class__ to be whatever class declaration I am in. I'm well aware I can just add className after funcName but I want to keep this as simple as possible when actually using it. My RPC manager calls rpc_foo and passes a pointer to an object of the class I declared it in. Essentially I need to know how to determine the actual class of that void* parameter.
In Visual Studio 2012 you can use that trick, but it will not work in gcc, at least for now.
template<typename base_t>
static auto GetFunctionBaseType(void(base_t::*)())->base_t;
struct TBase
{
template<typename T> void GetBaseType();
typedef decltype(GetFunctionBaseType(&GetBaseType<void>)) this_t;
static void rpc_func1(void * ptr)
{
((this_t*)ptr)->func1();
}
};
I believe that what you're asking for at heart is simply not possible: C++ is a statically typed language, which means that all type information must be available at compile time (runtime polymorphism notwithstanding). That is, when you say,
T x;
then the type T must be known at compile time. There is no such thing as "T_from_user() x;", whereby the actual type of a variable is determined at runtime. The language just isn't designed that way.
Usually if you're asking such a question that's an indicator that you're going about a problem the wrong way, though. Typical solutions for polymorphic situations involve class inheritance and virtual functions, or other sorts of lookup tables, or really any number of different approaches. Your request for a preprocessor macro also indicates that something is off. Any programming language has its idioms, and veering too far from those is usually a bad idea.
What you want to do is called Reflection. It was implemented in .NET (I don't know, maybe in Java too) and is going to be implemented in future standards of C++.
It seems you have a few unrelated classes that have a number of methods in common (the ones that can be sent as the funcName argument in your example).
Instead of having these unrelated classes, consider a polymorphic approach. For example, let's say the functions that you support are func1 and func2, then you can work this out in this way:
class BaseClass {
public:
virtual void func1(RpcManager::RpcParamsContainer args) = 0;
virtual void func2(RpcManager::RpcParamsContainer args) = 0;
};
class MyClass1 : public BaseClass {
public:
virtual void func1(RpcManager::RpcParamsContainer args) { /* func1 implementation here */ }
virtual void func2(RpcManager::RpcParamsContainer args) { /* func2 implementation here */ }
};
class MyClass2 : public BaseClass {
public:
virtual void func1(RpcManager::RpcParamsContainer args) { /* func1 implementation here */ }
virtual void func2(RpcManager::RpcParamsContainer args) { /* func2 implementation here */ }
};
With the above design your can pass a BaseClass* around, and you can call func1 or func2 without having to do any casts, and the compiler will find the correct version to invoke. For example, in your macro you could do something like this:
#define RPC_FUNCTION(funcName) static void rpc_##funcName(BaseClass* oOwner, RpcManager::RpcParamsContainer params){ oOwner->funcName(params); };
I hope this helps!
Are searching for the function macro? It's a macro that expands to the current function name.
__FUNCTION__
No, a static method can only see static members of the class. It doesn't make sense for it to access instance members (as in, standard variables etc) as they don't exist unless the class has been instantiated.
It seems like you want something like the Singleton design pattern. This allows for only a single instance of the class to exist at a time.
Another way would be to have a static list of all instances of a class, then in the class constructor, add the this pointer to that list. As I say though, static members cannot access instance variables, as they may not exist at all.
I suppose the greater question is this: why do you need to access an instance variable from a static member? If you require access to an instance member, you should be calling the function in the context of the current instance, otherwise you're breaking the OOP paradigm pretty hard.

Access class functions from another thead?

I have a function in my class that creates a thread and gives it arguments to call a function which is part of that class but since thread procs must be static, I can't access any of the class's members. How can this be done without using a bunch of static members in the cpp file to temporarily give the data to be manipulated, this seems slow.
Heres an example of what I mean:
in cpp file:
void myclass::SetNumber(int number)
{
numberfromclass = number;
}
void ThreadProc(void *arg)
{
//Can't do this
myclass::SetNumber((int)arg);
}
I can't do that since SetNumber would have to be static, but I instance my class a lot so that won't work.
What can I do?
Thanks
Usually you specify the address of the object of myclass as arg type and cast it inside the ThreadProc. But then you'll be blocked on how passing the int argument.
void ThreadProc(void *arg)
{
myclass* obj = reinterpret_cast<myclass*>(arg);
//Can't do this
obj->SetNumber(???);
}
As you said this is maybe not only a bit slow but it also clutters the code. I would suggest to use boost::bind for argument binding and to create the threads in an os independent way (for your own source at least) you could use boost::thread. Then no need for static methods for your threads.
Now in the C++0x standard, here a small tutorial
I would suggest you to make a friendly class with a static method for this purpose. It looks much cleaner. Eg:-
class FriendClass
{
public:
static void staticPublicFunc(void* );
};
Now befriend the above class in your main class ...
class MyClass
{
friend void FriendClass::staticPublicFunc(void*);
};
This should enable you to set the friend-function as the thread-function and access the class per instance in each thread. Make sure to synchronize your access to data visible across threads.