When writing this function:
let make_new_instance class_name = new class_name
I get the error "unbound class class_name", however, this is just a function definition, not a function call. How do I delay the "new" so that it doesn't attempt to construct an object until the function is called?
You cannot do it in OCaml, which is a statically typed language. Classes must be statically specified at new and cannot be used as arguments to function applications. (new is not even a function but a special form new <classname>.)
One way to parameterize classes is to use functors:
module A = struct
class c = object
method x = 1
end
end
module Make(A : sig class c : object method x : int end end) = struct
let make_new_instance () = new A.c
end
module MakeA = Make(A)
but I am afraid this is far from you want.
This isn't really something you can do in OCaml. One way to see this is to think about what you would pass to the function. A class name is a type, not a value. Another way is to note that a function can only return values of one type. Different classes have different types.
Did you try to change you class_name parameter to unit ?
let make_new_class_name () = new class_name
Classes in a OCaml are like blueprints, but to create something, you usually do not start from blueprints, but go to factory. So, if you need a factory that creates an instances of certain class, then it can be done:
class blue_print x y = object ... end
let create_instance = new blue_print
let factory instance_maker x y = instance_maker x y
Of course, all this doesn't make big sense, since example is very reduced, but if it is coupled with some registry, where you store instace_makers, then you will get an abstract factory
I get the error unbound class class_name, however, this is just a function definition, not a function call. How do I delay the "new" so that it doesn't attempt to construct an object until the function is called?
The error you get comes from the fact that class_name here is the name of a function argument, but you try to have it carry the name of a class. In languages like PERL, PHP, or other similar languages, you have access at runtime to symbol tables, thus letting you define new functions, new classes, new variables, and reference them in variables. For instance, in PHP, the code:
<?php
function foo($var){ echo ${$var};}
$bar = "foo";
$bar($bar);
would render:
"Function"
by calling the function foo through the variable $bar.
In OCaml, you cannot do something like that with value names, in your precise case, the grammar strictly expects a class name after the keyword new (otherwise you would be confronted with problems typically encountered in dynamic languages, ie, how to check whether the variable content is really a class) - Jeffrey Scoffield is spot on there. However, being a functional language, the usual way is to pass around functions, and apply them to parameters in other functions:
class foo () = object
method m = "foo"
end
class bar () = object
method m = "bar"
end
Both class above have the same class type, and expect the same arguments to create instances of them, thus you may use them interchangeably without typing issues.
let mk_instance toggle : object method m : string end =
if toggle
then new foo ()
else new bar ()
the function mk_instance will produce either an instance of foo or an instance of bar depending on the value of toggle.
You can use that to your advantage by creating functions wrapping instantiations of foos and bars, and then pass them around:
let mk_foo = new foo
let mk_bar = new bar
let mk_instance mk : object method m : string end = mk ()
The above is trivial, but you may certainly envision cases with more involved class definitions, and with closures, it is always possible to align function signatures to make this easier, or embed them in sum types to indicate different possibilities.
Related
I am relatively new to C++ and I am working on a personal project for practicing where I need to create a class that can take function pointers with different signatures.
The idea is that each instance of the class will store a pointer to a specific function and can call that function whenever I want.
To give a better idea of what I want, let me explain with a little bit more detail what I am trying to do. The project I am working on is a very basic console game and the object I am trying to create is an object that would store details on each location the player can access in the game.
(DISCLAIMER: I know that most of what I describe later is probably an overkill for a basic console game. I can easily make the whole game in a couple of files using just simple functions and I know how to do that. But the idea here is that I wanted to practice more advanced C++ techniques without having to figure out a complex project. So, since I know how to make a basic console game, I thought it would be a good idea to try and figure out how to achieve the same result but with more advanced techniques)
One of the details that I think should be stored is what happens in each location, basically the text that is output to the screen describing what happens and prompting the user to take action.
Since this would be different for each location, I can't just declare and implement a function in the class.
One way of solving this issue is to create a base class with a virtual function and then implement this function in a series of derived classes, each defining a new location.
The problem I have with this approach is that it makes each location a class that can be inherited further and instanced, which I don't need as I will only have 1 instance of each location.
I can of course just create 1 instance of the class, but I wanted to see if there is a way to avoid having to create separate classes for each location.
This why I started thinking of function pointers.
Now, I know I can declare a function pointer and initialise it in a class like that:
class Test
{
public:
Test(void (*p)())
: print{p}
{}
private:
void (*print)();
};
That works fine as long as the function returns void and accepts no arguments.
So, I thought maybe I can do that with a template:
template <typename Function>
class Test
{
public:
Test(Function *p)
: print{p}
{}
Function *print;
};
This actually works well. I can now have a class that accepts different functions with different return types.
I can create instances of the class in the following way:
void print();
Test<void ()> a {print};
However, I have one problem with this approach. Because it is a class template, I can't have a pointer that I want to use to point to instances of Test class regardless of the function that is passed to them.
For instance, if I declare the following pointer:
Test<void ()> *b = &a;
There is no way to re-assign that pointer to another instance of Test class unless the function pointer passed to it also returns void and accepts no arguments. Otherwise, I have to create a new pointer.
Is there a way to avoid that? Is there a better way of achieving what I am looking for than using function pointers?
Thank you very much and sorry for the long message.
There is no way to re-assign that pointer to another instance of Test class unless the function pointer passed to it also returns void and accepts no arguments.
And how would you expect that to work? Each Test has a different signature for its print method. In the example below, if you assigned action2 to action1, then how would it know what to pass to the print function?
void fun1() {}
void fun2(int) {}
void test() {
Test<void()> action1= &fun1;
action1.print();
Test<void(int)> action2= &fun2;
action2.print(42);
}
What you want is really simple, thanks to improvements in C++11: std::function<void()>.
Whenever you need to pass some arguments to the function, you'd use a lambda, potentially with captures:
#include <functional>
void fun1() {}
void fun2(int) {}
using Action = std::function<void()>;
int main() {
class MyObject { public: void doSomething() {} } obj;
Action action1;
action1 = fun1;
action1 = []{ fun2(42); };
action1 = [&obj]{ obj.doSomething(); }; // obj captured by reference
}
So that's pretty much what you should do.
Now of course you may ask "hey, but what if I wanted to implement something like std::function myself"? It's not a trivial task, if you want to get full functionality of std::function, including small object optimization (i.e. std::function usually doesn't allocate unless the functor it wraps is "big").
I wanted to see what can I do if I had a reason to have the each game location using a function that have different return types.
You chose to use a common abstraction, i.e. some class (like Action) that you can always call the same way, and get to do various things. So, what would you like the following code to do?
Action someAction;
int result = someAction();
std::string result = someAction();
Now suppose that e.g. someAction has captured a void() function. What should the code that assigns the "result" to an integer or a string do? And how would you protect from mistakes, e.g. if you really wanted someAction() to return an int, but you accidentally used one that returns nothing?
Remember that the compiler has to generate code for all of the sites where you call someAction, so it needs to know what to do ahead of time, even if you may otherwise ensure that no "incorrect" calls are made.
You could implement a custom Action class on top of std::function that could support std::optional<ResultType> instead of ResultType. That way, if the actual result of the functor wrapped in Action was convertible to that ResultType, you'd get a non-null optional, otherwise the optional would be null. And the list of supported result types would need to be pre-determined, i.e. the compiler wouldn't be able to dynamically add them, but adding a new type should amount to passing an additional type as a template argument, so it'd be easy to support quite many types.
All the googling I've done so far has turned up things that are very close but just aren't quite cutting it for what I'm trying to do.
Let me describe this in the most basic way possible:
Imagine you have a C++ class
class A
{
public:
int Method();
int Variable;
};
Now imagine you instantiate A* Foo;
Now imagine you have a .lua file with this 3 line function:
function Test()
local n = Foo:Method();
Foo.Variable = 0;
local m = Foo.Variable;
end
How can you bind the object A* to lua such that all those things are doable?
Pseudocode-wise, my first attempt went like this, partly from copy pasting examples:
In a function only called once, regardless of the number of instances of A:
create newmetatable( MT )
pushvalue( -1 ) (i dont really get this)
setfield( -2, "__index" )
pushcfunction with a static version of Method that unpacks the A* pointer from checkudata
setfield( -2, "Method" )
In an init function called for each instance, e.g. Foo:
create a pointer to Foo with newuserdata
setmetatable( MT )
setglobal with Foo to make the name available to lua
In a test function in main:
pcall a test function with the 3 lines of .lua mentioned above, by global name
When doing this, Foo:Hide(); successfully called my static function, which successfully unpacked the pointer and called its member Hide().
So far so good for :Method().
Then I tried to support the .Variable access. Everyone seemed to be saying to use metatables again this time overriding __index and __newindex and make them a sort of generic Get/Set, where you support certain keys as valid variable links e.g. if( key == "Variable" ) Variable = val;
This also worked fine.
The problem is trying to put those two things together. As soon as you override __index/__newindex with a getter/setter that works on Variable, the Method() call no longer calls the Method() static function, but goes into the __index function you bound instead.
All of that said, how does one support this seemingly basic combination of use cases?
Actual code snippets would be much more appreciated than purely theoretical chatter.
Reminder: please respond using the basic C API only, not third party stuff.
the Method() call no longer calls the Method() static function, but
goes into the __index function you bound instead.
So program it so that if the key exists in the table, return that first, else go for getter/setter.
In C++ there are just objects and classes, where objects are instances of classes.
In Python, a class definition (i.e., the body of a class) is called an object.
And, the object in C++ is called instance in python.
Check this
Am I wrong?
EDIT : Actually can someone explain with example difference of object vs instance
EDIT : In python, everything will inherit from object class & hence everything is an object (i.e object of object class).
A Class is also an object (i.e object of object class).
Instance is the name used to call the object of any class.(a.k.a c++ object).
Please refer this
In Python, a class definition (i.e., the body of a class) is called an object
Actually, this is still called a class in Python. That's why you define it like this:
class Foo(object):
pass
The class keyword is used because the result is still called a class.
The word object is in parentheses to show that Foo is derived from the class called object. Don't be confused -- any existing class could be used here; more than one, in fact.
The reason you usually derive classes from object is a historical accident but probably is worth a detail. Python's original object implementation treated user-defined classes and built-in types as slightly different kinds of things. Then the language's designer decided to unify these two concepts. As a result, classes derived from object (or from a descendant of object) behave slightly differently from classes that are not derived from object and are called new-style classes. Old-style classes, on the other hand, were ones defined like this:
class Foo:
pass
class Bar(Foo):
pass
Note these do not inherit from object or from anything else that inherits from object. This makes them old-style classes.
When working with Python 2.x, your classes should almost always inherit from object, as the new-style objects are nicer to work with in several small but important ways.
To further confuse things, in Python 3.0 and later, there are no old-style classes, so you don't have to derive from object explicitly. In other words, all the above classes would be new-style classes in Python 3.x.
Now, back to the matter at hand. Classes are objects because everything is an object in Python. Lists, dictionaries, integers, strings, tuples... all of these are objects, and so are the building blocks of Python programs: modules, functions, and classes. You can create a class using the class keyword and then pass it to a function, modify it, etc. (For completeness, you can also create a class using the type() function.)
A class is a template for building objects, which are referred to as instances. This part you already know. You instantiate objects similar to calling a function, passing in the initial values and other parameters:
mylist = list("abc") # constructs ["a", "b", "c"]
Behind the scenes, this creates an instance, then calls the new instance's __init__() method to initialize it. Since everything's an object in Python, instances of a class are also objects.
One last thing you might want to know is that just as classes are templates for building objects, so it is possible to have templates for building classes. These are called metaclasses. The base metaclass is called type (that is, an ordinary new-style class is an instance of type).
(Yes, this is the same type that I mentioned earlier can be used to create classes, and the reason you can call it to create classes is that it's a metaclass.)
To create your own metaclass, you derive it from type like so:
class mymeta(type):
pass
Metaclasses are a fairly advanced Python topic, so I won't go into what you might use them for or how to do it, but they should make it clear how far Python takes the "everything's an object" concept.
Terminology-wise, classes and instances are both called objects in Python, but for you as a regular Python programmer this is of no importance. You can see Python's classes and instances pretty much as C++'s classes and instances:
class MyClass:
data = 1
mc = MyClass()
MyClass is a class and mc is an instance of class MyClass.
Python is much more dynamic in nature than C++ though, so its classes are also objects. But this isn't something programmers usually are exposed to, so you can just not worry about it.
Everything in Python is an object. Even classes, which are instances of metaclasses.
Since you asked for "english please", I'll try to make it simple at the cost of detail.
Let's ignore classes and instances at first, and just look at objects.
A Python object contains data and functions, just like objects in every other object oriented programming language. Functions attached to objects are called methods.
x = "hello" #now x is an object that contains the letters in "hello" as data
print x.size() #but x also has methods, for example size()
print "hello".size() #In python, unlike C++, everything is an object, so a string literal has methods.
print (5).bit_length() #as do integers (bit_length only works in 2.7+ and 3.1+, though)
A class is a description (or a recipe, if you will) of how to construct new objects. Objects constructed according to a class description are said to belong to that class. A fancy name for belonging to a class is to be an instance of that class.
Now, earlier I wrote that in Python everything is an object. Well, that holds for stuff like functions and classes as well. So a description of how to make new objects is itself an object.
class C: #C is a class and an object
a = 1
x1 = C() #x1 is now an instance of C
print x1.a #and x1 will contain an object a
y = C #Since C is itself an object, it is perfectly ok to assign it to y, note the lack of ()
x2 = y() #and now we can make instances of C, using y instead.
print x2.a #x2 will also contain an object a
print C #since classes are objects, you can print them
print y #y is the same as C.
print y == C #really the same.
print y is C #exactly the same.
This means that you can treat classes (and functions) like everything else and, for example, send them as arguments to a function, which can use them to construct new objects of a class it never knew existed.
In a very real sense, everything in Python is an object: a class (or any
type) is an object, a function is an object, a number is an object...
And every object has a type. A "type" is a particular type of object (a
class, if you wish), with additional data describing the various
attributes of the type (functions, etc.). If you're used to C++, you
can think of it as something like:
struct Type;
struct Object // The base class of everything.
{
Type* myType;
// Some additional stuff, support for reference counting, etc.
};
struct Type : Object
{
// Lots of additional stuff defining type attributes...
};
When you define a new class in Python, you're really just creating a new
instance of Type; when you instantiate that class, Python initializes
the myType member with a pointer to the correct instance of Type.
Note, however, that everything is dynamic. When you define a type
Toto (by executing a class definition—even defining a type is a
runtime thing, not compile time, as in C++), the Python interpreter
creates an instance of Type, and puts it in a dictionary
(map<string, Object*>, in C++ parlance) somewhere. When the interpreter
encounters a statement like:
x = Toto()
, it looks up Toto in the dictionary: if the Object referred to has
the type Type, it constructs a new instance of that object, if it has
type Function (functions are also objects), it calls the function.
(More generally, a type/class may be callable or not; if the type of the
Object found in the dictionary under Toto is callable, the Python
interpreter does whatever the object has defined "call" to mean. Sort
of like overloading operator()() in C++. The overload of
operator()() for Type is to construct a new object of that type.)
And yes, if you come from a classical background—strictly procedural,
structured, fully-compiled languages, it can be pretty confusing at
first.
I am using tolua++ to export some C++ classes to Lua.
My understanding that each class is 'implemented' on the lua side, as a lua table. I am wondering if it is possible therefore, to add new (Lua) methods to the C++ object table so that I can achieve the effect of adding new methods to the C++ class.
Assume that I am exporting the class Foobar.
Methods of Foobar will be accessisble in Lua as follows:
Foobar:method1()
Foobar:method2()
...
etc.
I would like to be able to add new methods (newmethod1, and newmethod2) to the Foobar table "object"
I have the following questions:
Is it possible to 'extend' the functionality of an exported C++ object in the manner I described above?
How would one go about add new functions to the Foobar table? (I am relatively new to Lua)
Yes, It is possible to add new methods to an existing exported class.
Foobar is just a plain table, so you can attach methods onto it as you would any other table. [1]
Foobar["extra_method"] = function (self, arg1, arg2) print(arg1, arg2) end
and now you can do:
Foobar:extra_method(1,2)
and 1 2 will be displayed.
[1] tolua++ works somewhat oddly. It creates one main table for each class, which is what you see as Foobar, that holds both the static member functions of the class (e.g. Foobar:new()) and the instance member functions of the class (e.g. what Foobar:method1() likely is). The : operator in lua is syntactic sugar; a:b() is converted to a.b(a). This means when you call Foobar:new(), it is transposed to Foobar:new(Foobar), thus the self argument is the Foobar table. When you create an object of type Foobar, and then call method1() on it, self will be that object. Thus, adding a new method method3 to the Foobar table will allow you to do Foobar:method3() and obj = Foobar:new(); obj:method3(), although the former will give an error. Thus, this answer only works for tolua++.
Edit: to address comment
Let me use actual code here. So let's assume we have a class declaration of Foobar that looks like:
class Foobar {
public:
void method1();
static void method2();
};
When tolua++ generates the lua binding code for this class it's going to give you a table with the following methods
new() - Call as Foobar:new() to create an instance of Foobar.
delete() - Call as instance:delete() to destroy an instance of Foobar.
method1() - Call as instance:method1() to run method1 on instance.
method2() - Call as Foobar:method2() to run method2.
However, tolua++ doesn't actually use two different tables (one for the methods that should be attached to the class itself and one for the methods of the instance of that class). Instead, it merges the two together, so it's possible to run Foobar:method1() and instance:new()... even though that's not how the methods should be used. Thus, there is no difference between how static methods are used and how instance methods are used. Syntactically, it's also the same. (I personally feel that this is a problem with tolua++.)
If you're looking for an example, here is how you should be calling these functions from within lua:
obj = Foobar:new()
print( obj:method1() )
obj:delete()
I don't know if there is an official name for this, but I have been playing with what I like to call the "self-factory" pattern. Basically, it's when an abstract base class acts as a factory for itself. Let me explain:
I have Foo objects and Bar objects in my system, which are used via interfaces FooInterface and BarInterface. I need to give my clients the right type of Foo and Bar. The decision of which concrete Foo object to create is made at compile time. For example, if you compile on win32, you want to only create Win32Foo objects, and if you compile on OSX you want to only create OSXFoo objects and so on. But, the decision of which concrete Bar object to create is made at runtime, based on a key string.
Now, my question is about the best way to implement this scheme. One way I come up with uses regular factories:
shared_ptr<FooInterface> foo = FooFactory::create();
shared_ptr<BarInterface> happyBar = BarFactory::create("Happy");
shared_ptr<BarInterface> sadBar = BarFactory::create("Sad");
Another way is to use what I call "self-factories":
shared_ptr<FooInterface> foo = FooInterface::create();
shared_ptr<BarInterface> happyBar = BarInterface::create("Happy");
shared_ptr<BarInterface> sadBar = BarInterface::create("Sad");
What are the pros and cons of each approach, both from a usability standpoint and from an architectural standpoint?
I'd make an improvement:
shared_ptr<FooInterface> foo = Factory<FooInterface>::create();
shared_ptr<BarInterface> happyBar = Factory<BarInterface>::create("Happy");
shared_ptr<BarInterface> sadBar = Factory<BarInterface>::create("Sad");
You'd declare:
template <class I>
struct Factory { };
And then for each interface that needs a factory, you'd do this:
template <>
struct Factory<FooInterface>
{
static FooInterface create();
};
This allows you to keep the factory implementation separate from the interface declaration, but still using the type system to bind them at compile time.
Factories have two common uses:
1) Decide dynamic polymorphic type at runtime, based on parameters and/or global state (such as configuration). Your pattern does this.
2) Dependency injection: rather than using a static function to create objects, use a factory object, so that the type of object returned can be configured by the caller, by passing in whatever factory they want. Neither of these patterns provides this. Furthermore, your second pattern doesn't even allow static dependency injection (by having template functions that take a factory class as a template parameter), because the interface and the factory are the same.
So one con of your pattern (and of your regular factories) is that dependency injection isn't really supported. There is one and only one function to call to get an object that's a FooInterface, and that is FooInterface::create(). I'll not argue why dependency injection is useful, just point out that if you build this way, you can't use it.
Usually factories are responsible for creating objects of entire class hierarchies. So in your example you would have a Win32Factory, OSXFactory etc. One advantage of this is that you have to select the specific implementation ( win32/unix/etc) just once -- during factory creation, but if you use class interfaces, you have to supply the OS info all the time.
If you only have two classes (Foo and Bar) I'm not sure, if it's worth the effort to create factories for them and not just use a create method of the interfaces.
Oh, and when an interface has a method for creating objects of it's type, it's called the factory method pattern.