I want create object at run-time as in JavaScript:
person=new Object();
person.firstname="John";
I'm going to parse json and save to object. Methods will be known in advance and compiled.
I created this simple example and I would like to know if I'm going the right way.
adding and call method by string; function male and female will be added to object as methods to object.
Now in object is property gender, but later I want to do the same as with the functions. by methods setProperty and getProperty declared in Object. is it a good idea?
typedef struct method
{
(void)(*method_fn)(Object * _this, string params);
string method_name;
} method;
class Object{
private:
vector<method> methods;
public:
string gender;
Object(){};
~Object(){};
void addMethod(method metoda);
bool callMethod(string methodName,string params);
};
void male(Object *_this,string params) {
_this->gender="Male";
}
void female(Object* _this,string params) {
_this->gender="Female";
}
void Object::addMethod(method metoda)
{
methods.push_back(metoda);
}
bool Object::callMethod(string methodName,string params){
for(unsigned int i=0;i<methods.size();i++)
{
if(methods[i].method_name.compare(methodName)==0)
{
(*(methods[i].method_fn))(this,params);
return true;
}
}
return false;
}
using and it is work.
int _tmain(int argc, _TCHAR* argv[])
{
Object *object1 = new Object();
Object *object2 = new Object();
method new_method;
new_method.method_fn=♂
new_method.method_name="method1";
object2->addMethod(new_method);
new_method.method_fn=♀
new_method.method_name="method2";
object2->addMethod(new_method);
object1->callMethod("method1","");
object2->callMethod("method2","");
return 0;
}
You're better off using a map, and using references:
class Object {
public:
Object() {}
~Object() {}
typedef void (*Method)(Object& _this, const std::string& params);
void setMethod(const std::string& name, Method fn) { methods[name] = fn; }
bool callMethod(const std::string& name, const std::string& params);
private:
std::map<std::string, Method> methods;
std::map<std::string, std::string> properties;
};
bool Object::callMethod(const std::string& name, const std::string& params)
{
// Look for it.
// Note: in C++11, you can do this instead:
// auto methodIter = methods.find(name);
std::map<std::string, Method>::iterator methodIter = methods.find(name);
if(methodIter == methods.end())
return false;
// Found it.
(*(methodIter->second))(*this, params);
return true;
}
Note that I added properties which does the same thing as methods except it maps names to strings instead of functions. This replaces your string gender; stuff.
Anyway, just some small changes to your main function, to remove the need for a method structure:
int _tmain(int argc, _TCHAR* argv[])
{
Object *object1 = new Object();
Object *object2 = new Object();
object1->addMethod("method1", &male);
object2->addMethod("method2", &female);
object1->callMethod("method1", "");
object2->callMethod("method2", "");
return 0;
}
P.S. I used the std:: prefixed versiojns of the standard type names because you should never have using namespace std; or similar in a header file.
It's mostly OK. You've created dynamic containers for your methods and their associated names. This is A LITTLE like what a dynamic language would do, behind the scenes.
What you can do to improve it is use hash maps, for more speed. For example:
typedef void (*Method)(Object& _this, const string& params);
typedef std::unordered_map<string, Method> NameToMethodMap;
typedef std::unordered_map<string, string> NameToValueMap;
class Object {
private:
NameToMethodMap methods;
public:
NameToValueMap attributes;
void addMethod(const std::string& name, Method& method) {
// TODO: check that name isn't in there first
methods[name] = method;
}
};
int main() {
Object o;
o.attributes["gender"] = "male";
}
Related
I'm very new in C++, but I'm working on a little framework of mine.
For this framework, I need to load various types of Resources and I would love to write it such it would be very easy to add new Resources without having to create managers for every one of them.
So I was thinking like this:
I need base BaseResource class from which I can then inherit other resource types
class BaseResource {
uint32_t resource_id;
std::string name;
std::string path;
public:
uint32_t get_id() {
return resource_id;
}
const std::string& get_name() {
return name;
}
const std::string& get_path() {
return path;
}
};
Then what I need is some kind of base BaseResourceManager templated for Resource
template<class T>
class BaseResourceManager{
// path = name
std::vector<T> _resources;
std::map<std::string, uint32_t> _path_map; //
public:
void load(std::string path) {
// load from file and call T with name
_path_map.insert();
}
T& get(uint32_t idx) {
return _resources[idx];
}
T& get_by_name(std::string name) {
return _resources[_path_map[name]];
}
void delete(uint32_t idx) {
std::string name = resources[idx].get_name();
_resources[idx] = null_ptr;
_path_map[name] = nullptr; // ERASE ??
}
};
But now I'm kind of stuck while making something, what could glue multiple BaseResourceManager<T1>, BaseResourceManager<T2> together.
All I could do, but it is wrong, is this main ResourceManager
class ResourceManager {
// managers
std::vector<BaseManager> managers;
public:
ResourceManager() {
}
void init() {
}
void register_manager(BaseManager&& man) {
managers.push_back(man);
}
template <typename T, size_t i>
T get() {
return dynamic_cast<T>(managers[i]);
}
};
I think it would be a good idea to store in _managers some kind of pointer to heap-allocated managers,
and also what I couldn't solve was creating get() function only with one template, somehow automatically create a sequence of numbers for every type as a second template.
How can one pass a non moveable object to a std::function? One easy enough alternative is passing a std::reference_wrapper which would create the need for the lifecycle of function be dependant on the object. Example code follows to explain the issue better.
class Player {
std::atomic_int runs {0};
std::string name;
public:
Player(std::string&& name) : name(std::move(name)) {} //...
void inc() { ++runs;}
};
class PlayerStats {
std::array<std::unique_ptr<Player>,2> players;
public:
PlayerStats() {
for(int i = 0; i<2 ; i++)
players[i] = std::unique_ptr<Player>(new Player{"player"+std::to_string(i)});
}
Player* const operator() (int index) const {
return players[index].get();
}
};
using player_total_f = std::function<Player* const(int index)>;
class GameStats {
std::string game;
std::string date;
player_total_f f;
public:
GameStats(std::string&& game, std::string&& date, player_total_f&& _f) :
game(std::move(game)), date(std::move(date)), f(std::move(_f)) {}
};
int main(int argc, char *argv[])
{
PlayerStats st;
//GameStats("game1","10.11",std::ref(st)); //this seems like the only possibility, no way to make GameStats own the functor
return 0;
}
How can I set the function here to PlayerStats, given that it is non copyable, a std::ref seems to be like the only possibility?
template<class F>
auto shared_function( F&& f ){
auto spf=std::make_shared<std::decay_f<F>>(std::forward<F>(f));
return [spf=std::move(spf)](auto&&...args)->decltype(auto){
return (*pf)(decltype(args)(args)...);
};
}
own it in a shared ptr. Changes semantics a bit, but fixes it.
Or write your own non-copying std function.
I am writing an interface for several I/O classes.
There is a function that looks for information in different kinds of files (sometimes html, sdb, txt, ...):
bool Search(std::string file, std::string field)
However, one of these requires an additional parameter to complement the SQL query. In this case the sdb needs to specify in what table the field is located.
I am trying something like the following (it does not compile, I am aware):
class fileIO{
public:
virtual ~FileIO(){};
virtual bool Search(std::string file, std::string field,
std::string additional = 0 /* for sdb only */) = 0;
}
class readHTML : fileIO{
public:
bool Search(std::string file, std::string field); //does NOT override virtual method
Is there anything that can give me the behavior I am looking for?
Is such strategy according to C++ standards?
What else could I add to replace such enforcement on the interface?
I am sorry if the title is misleading, I am looking for an alternative with that behavior. I could not find it so far.
You don't need it, I'd say.
At the caller site, there is only two possibilities: you know your specific fileIO instance is a sdbIO or you don't. If you do, you can call an overloaded version of Search defined in sdbIO which takes this additional info. If you don't, you don't and sdbIO::Search should be defined in terms of its overloaded version.
struct fileIO
{
virtual bool Search(std::string file, std::string field) = 0;
}
struct sdbIO : fileIO
{
bool Search(std::string file, std::string field, std::string additional);
bool Search(std::string file, std::string field) override
{
Search(file, field, "");
}
};
At the caller site:
void f(fileIO& io)
{
// I know this is a sdb:
dynamic_cast<sdbIO&>(io).Search("/file", "text", "WHERE answer=42");
// I don't
io.Search("/file", "text");
}
notes: do you really need a copy of those strings?
You can hide the virtual function in the non-public interface and make the public interface (with the default argument) non-virtual.
struct Interface
{
...
// public interface calls the abstract members.
bool Search(string const&a, string const&b, string const&c = "")
{
if(c.empty() && need_third_string())
throw runtime_error("search requires an additional string argument");
return search(a,b,c);
}
protected:
virtual bool need_third_string() const = 0;
virtual bool search(string const&, string const&, string const&) const=0;
};
with obvious derivations:
struct A : Interface
{
protected:
bool need_third_string() const override
{ return false; }
bool search(string const&a, string const&b, string const&) const override
{ /* search ignoring third argument */ }
};
struct B : Interface
{
protected:
bool need_third_string() const override
{ return true; }
bool search(string const&a, string const&b, string const&c) const override
{ /* search ignoring using all 3 arguments */ }
};
I don't see any problem with above two way to handle things. Still, I have just one more.
#include<bits/stdc++.h>
#include <stdexcept>
using namespace std;
typedef struct
{
std::string arg1;
std::string arg2;
std::string arg3;
} Param;
class FileIO{
public:
virtual ~FileIO(){};
virtual void Search(Param param) = 0;
};
class ReadHTML : public FileIO{
public:
void Search(Param param)
{
if(param.arg3.length() > 0) // Some logic to handle things here.
search3(param.arg1, param.arg2, param.arg3);
else
throw std::runtime_error("Bad call with param");
}
private:
void search3(std::string arg1, std::string arg2, std::string arg3)
{
std::cout << " I am called with Html::Search3" << std::endl;
}
};
class ReadTxt : public FileIO{
public:
void Search(Param param)
{
if(param.arg1.length() && param.arg2.length()) // Some logic to handle things here.
search2(param.arg1, param.arg2);
else
throw std::runtime_error("Bad call with param");
}
private:
void search2(std::string arg1, std::string arg2)
{
std::cout << " I am called with Txt::Search2" << std::endl;
}
};
// Driver program to test above function
int main()
{
FileIO *io = new ReadHTML();
Param paramHtml = {"a", "b", "c"};
io->Search(paramHtml); // Put some try .. catch
Param paramTxt = {"a", "b"};
io = new ReadTxt(); // Put some try...catch
io->Search(paramTxt);
return 0;
}
I have an object, every member variable in this object has a name which I can acquire it by calling get_name() ,what I want to do is concatenate all the names of the member variables in alphabetical order, then do something. for example:
class CXMLWrapper<class T>
{
public:
CXMLWrapper(const char* p_name) : m_local_name(p_name)
{
}
//skip the get_name(), set_name() and others
private:
string m_local_name;
T m_type_var;
}
class object
{
public:
object() : m_team("team"), m_base("base")
{
}
public:
CXMLWrapper<string> m_team;
CXMLWrapper<string> m_base;
...
}
I have to hard-code like this:
object o;
string sign = o.m_base.get_name();
sign += o.m_team.get_name();
I need a function to do this instead of copying and pasting when the object varies. Anyone has an idea?
One way to do this in normal C++, provided all of the members belong to the same class or are derived from some base class will be to use variable number of arguments to a function. An example follows.
#include <stdarg.h>
string concatenateNames(int numMembers, ...)
{
string output;
va_list args;
va_start(args, numMembers);
for(int i = 0; i < numMembers; i++)
{
MemberClass *pMember = va_arg(args, MemberClass*);
output += pMember->get_name();
}
va_end(args);
return output;
}
class Object
{
public:
MemberClass x;
MemberClass y;
MemberClass z;
};
int main()
{
Object o;
string sign = concatenateNames(3, &o.x, &o.y, &o.z);
}
If the types of all the members are different, you can look into variadic templates of C++11x: http://en.wikipedia.org/wiki/Variadic_Templates, but I can't seem to find a way to do otherwise.
If variables which have name have a same type (or these types belongs one hierarchy) you can use map of these vars. Is not good way, but maybe it helps you
Example
class object
{
public:
object() //: m_team("team"), m_base("base")
{
this->vars["m_team"] = CXMLWrapper<string>("team");
//.....
}
public:
map<string, CXMLWrapper<string> > vars;
/*CXMLWrapper<string> m_team;
CXMLWrapper<string> m_base;*/
...
}
object o;
string sign;
for(auto& x : o.vars)//i cannot remember syntax of for of map
sign += x.get_name;
PS Sorry for my writing mistakes. English in not my native language.
One method is to have an external library of member names which the CXMLWrapper class updates:-
class BaseXMLWrapper
{
public:
void ListMembers (const char *parent)
{
// find "parent" in m_types
// if found, output members of vector
// else output "type not found"
}
protected:
void RegisterInstance (const char *parent, const char *member)
{
// find 'parent' in m_types
// if not found, create a new vector and add it to m_types
// find 'member' in parent vector
// if not found, add it
}
private:
static std::map <const std::string, std::vector <const std::string> >
m_types;
};
class CXMLWrapper <class T, const char *parent> : BaseXMLWrapper
{
public:
CXMLWrapper(const char* p_name) : m_local_name(p_name)
{
RegisterInstance (parent, p_name);
}
// you could override assignments, copy and move constructors to not call RegisterInstance
//skip the get_name() set_name()
private:
m_local_name;
}
class object
{
public:
object() : m_team("team"), m_base("base")
{
}
public:
CXMLWrapper<string, "object"> m_team;
CXMLWrapper<string, "object"> m_base;
...
};
This does add overhead to the construction of objects, but as it's only a constructor overhead it might not affect overall system performance much.
This looks like a "observe pattern", you just need to keep a single copy in object as a member variable "string name_;", and pass the name_s's reference into CXMLWrapper like this:
class CXMLWrapper<class T>
{
public:
CXMLWrapper(const string &name)
: local_name_(name)
{
}
//skip the get_name() set_name()
private:
const string &local_name_;
}
class object
{
public:
object()
: team_("team"),
base_("base"),
m_team(team_)
, m_base(base_)
{
}
public:
string team_;
string base_;
CXMLWrapper<string> m_team;
CXMLWrapper<string> m_base;
}
I have a class called Object which stores some data.
I would like to return it by reference using a function like this:
Object& return_Object();
Then, in my code, I would call it like this:
Object myObject = return_Object();
I have written code like this and it compiles. However, when I run the code, I consistently get a seg fault. What is the proper way to return a class object by reference?
You're probably returning an object that's on the stack. That is, return_Object() probably looks like this:
Object& return_Object()
{
Object object_to_return;
// ... do stuff ...
return object_to_return;
}
If this is what you're doing, you're out of luck - object_to_return has gone out of scope and been destructed at the end of return_Object, so myObject refers to a non-existent object. You either need to return by value, or return an Object declared in a wider scope or newed onto the heap.
You can only use
Object& return_Object();
if the object returned has a greater scope than the function. For example, you can use it if you have a class where it is encapsulated. If you create an object in your function, use pointers. If you want to modify an existing object, pass it as an argument.
class MyClass{
private:
Object myObj;
public:
Object& return_Object() {
return myObj;
}
Object* return_created_Object() {
return new Object();
}
bool modify_Object( Object& obj) {
// obj = myObj; return true; both possible
return obj.modifySomething() == true;
}
};
You can only return non-local objects by reference. The destructor may have invalidated some internal pointer, or whatever.
Don't be afraid of returning values -- it's fast!
I will show you some examples:
First example, do not return local scope object, for example:
const string &dontDoThis(const string &s)
{
string local = s;
return local;
}
You can't return local by reference, because local is destroyed at the end of the body of dontDoThis.
Second example, you can return by reference:
const string &shorterString(const string &s1, const string &s2)
{
return (s1.size() < s2.size()) ? s1 : s2;
}
Here, you can return by reference both s1 and s2 because they were defined before shorterString was called.
Third example:
char &get_val(string &str, string::size_type ix)
{
return str[ix];
}
usage code as below:
string s("123456");
cout << s << endl;
char &ch = get_val(s, 0);
ch = 'A';
cout << s << endl; // A23456
get_val can return elements of s by reference because s still exists after the call.
Fourth example
class Student
{
public:
string m_name;
int age;
string &getName();
};
string &Student::getName()
{
// you can return by reference
return m_name;
}
string& Test(Student &student)
{
// we can return `m_name` by reference here because `student` still exists after the call
return stu.m_name;
}
usage example:
Student student;
student.m_name = 'jack';
string name = student.getName();
// or
string name2 = Test(student);
Fifth example:
class String
{
private:
char *str_;
public:
String &operator=(const String &str);
};
String &String::operator=(const String &str)
{
if (this == &str)
{
return *this;
}
delete [] str_;
int length = strlen(str.str_);
str_ = new char[length + 1];
strcpy(str_, str.str_);
return *this;
}
You could then use the operator= above like this:
String a;
String b;
String c = b = a;
Well, it is maybe not a really beautiful solution in the code, but it is really beautiful in the interface of your function. And it is also very efficient. It is ideal if the second is more important for you (for example, you are developing a library).
The trick is this:
A line A a = b.make(); is internally converted to a constructor of A, i.e. as if you had written A a(b.make());.
Now b.make() should result a new class, with a callback function.
This whole thing can be fine handled only by classes, without any template.
Here is my minimal example. Check only the main(), as you can see it is simple. The internals aren't.
From the viewpoint of the speed: the size of a Factory::Mediator class is only 2 pointers, which is more that 1 but not more. And this is the only object in the whole thing which is transferred by value.
#include <stdio.h>
class Factory {
public:
class Mediator;
class Result {
public:
Result() {
printf ("Factory::Result::Result()\n");
};
Result(Mediator fm) {
printf ("Factory::Result::Result(Mediator)\n");
fm.call(this);
};
};
typedef void (*MakeMethod)(Factory* factory, Result* result);
class Mediator {
private:
Factory* factory;
MakeMethod makeMethod;
public:
Mediator(Factory* factory, MakeMethod makeMethod) {
printf ("Factory::Mediator::Mediator(Factory*, MakeMethod)\n");
this->factory = factory;
this->makeMethod = makeMethod;
};
void call(Result* result) {
printf ("Factory::Mediator::call(Result*)\n");
(*makeMethod)(factory, result);
};
};
};
class A;
class B : private Factory {
private:
int v;
public:
B(int v) {
printf ("B::B()\n");
this->v = v;
};
int getV() const {
printf ("B::getV()\n");
return v;
};
static void makeCb(Factory* f, Factory::Result* a);
Factory::Mediator make() {
printf ("Factory::Mediator B::make()\n");
return Factory::Mediator(static_cast<Factory*>(this), &B::makeCb);
};
};
class A : private Factory::Result {
friend class B;
private:
int v;
public:
A() {
printf ("A::A()\n");
v = 0;
};
A(Factory::Mediator fm) : Factory::Result(fm) {
printf ("A::A(Factory::Mediator)\n");
};
int getV() const {
printf ("A::getV()\n");
return v;
};
void setV(int v) {
printf ("A::setV(%i)\n", v);
this->v = v;
};
};
void B::makeCb(Factory* f, Factory::Result* r) {
printf ("B::makeCb(Factory*, Factory::Result*)\n");
B* b = static_cast<B*>(f);
A* a = static_cast<A*>(r);
a->setV(b->getV()+1);
};
int main(int argc, char **argv) {
B b(42);
A a = b.make();
printf ("a.v = %i\n", a.getV());
return 0;
}
It isn't really good practice to return an initiated object as it does go out of scope. There are rare instances that this is the desired option. It actually can be done if the class is a referencing counting smart pointer or some other smart pointer.
How does a reference-counting smart pointer's reference counting work?