Consider - fun A() call fun B() and vise versa and I implement A() before B(), like this:
fun A() =
B() ;
fun B() =
A() ;
In such case the SML/NJ interpreter prompts -
Error: unbound variable or c onstructor: B
How do I solve this? Maybe something like forward declaration?
(leave it that it cause infinite loop)
You can use the and keyword to declare mutually recursive functions.
fun A () = B ()
and B () = A ()
You also use the same keyword to make mutually recursive datatypes.
Note, usually you'll write function names with the first letter in lowercase:
fun a () = b ()
and b () = a ()
This helps with distinguishing between functions and value constructors.
There is no need as such to use a let binding for this. You can declare it at top level as well:
fun a () = b ()
and b () = a ()
Related
I am trying to write a compiler for a language that supports nested functions, for example:
func a()
int x;
func b()
int y;
{
// code of func b - both x and y are visible here
}
{
// code of func a - only x is visible here
}
I am using LLVM API in c++ to compile the code. My problem is that I don't know how to make variable x visible in function b, since to my knowledge llvm does not support nested function. The way I am declaring variable as of now is this function:
static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction, const std::string &VarName, Type *T) {
IRBuilder<> TmpB(&TheFunction->getEntryBlock(), TheFunction->getEntryBlock().begin());
return TmpB.CreateAlloca(T, 0, VarName.c_str());
}
As shown in the llvm tutorial https://llvm.org/docs/tutorial/LangImpl07.html#adjusting-existing-variables-for-mutation.
When using this declaration and trying to use an outside variable in a nested function this error pops up: Instruction does not dominate all uses!.
Is there a way to fix this?
LLVM does support structs, right? So here's what typical compilers do.
You need to create an anonymous struct with fields generated from every outer variable you reference. Then you create an anonymous function corresponding to b() that takes that struct as argument and operates on it. Basically you turn b() into a regular top-level function. Finally you transform a() code so that it creates the struct instance and calls the anonymous function. At this point further optimizations are possible. Be prepared: this is not easy at all, possibly a very advanced topic for code transformations.
For example
func a()
int x = 1;
func b() {
return x+1;
}
return b() + 2;
}
becomes
struct tmp {
int tmpx; // reference or value?
}
func tmp_b(tmp& instance) {
instance.tmpx += 1;
return instance.tmpx;
}
func a() {
int x = 1;
tmp instance(tmpx = x); // should it go by reference or value?
return tmp_b(instance) + 2;
}
As an alternative you can convert b() into b(int x) top-level function. But that approach is less flexible IMO. Or depending on context utilize both approaches, why not.
Note that all of that can probably be simplified if your language supports proper classes with methods and/or operator (in this case call operator) overloading.
That isn't a supported capability in C++.
If you are looking to access a variable in this way from a nested or any other function, pass a reference to it. :)
In this problem, assume that we have handled all pointers in a nice, careful manner - to prevent question bloat I don't want to include my cleanup code here!
Let's say we have two classes, Foo and Bar with class definitions as follows:
class Foo
{
public:
Foo();
void fooFn();
};
class Bar
{
public:
Bar();
void barFn();
};
Assume that it is necessary that Foo and Bar have no inheritance relationship, but we need to call both fooFn and barFn in response to some stimulus. We can create a controller class with a container from which to call fooFn and barFn on specific instances of Foo and Bar - a static std::vector for example - but we run into an issue: pointers to member functions of Foo and Bar instances are of different types.
By using a static vector< std::function<void()>* > in the controller class, we can make a workaround. Foo and Bar instances can have a function which adds pointers to the vector through a lambda function which captures this:
void Foo::registerFnPointer()
{
ControllerClass::function_vector.push_back( new [this](){ return this->fooFn(); } );
}
I have tested this method, and it appears to work without any problems. That said, I am concerned about the issues that could be caused by circumventing the type difference mentioned before... Am I worrying over nothing? Is there a better way to accomplish equivalent functionality?
The only problem I see has actually nothing to do with the functors but has to do with object lifetime. That is: I'm not sure how you ensure that you always de-register the functors registered with ControllerClass whenever an Foo or Bar instance gets destroyed.
You mention however that you do proper memory management.
In my opinion you do not need to store a pointer to function<void()>, you can simply store function as value (that is have a vector<function<void()>>).
Prior to C++11 and lambdas, to achieve the same effect you would have used a (boost) function also but you would would have used boost::bind with with the address of the fooFn and the first parameter bound to a pointer (or reference) to the Foo object instance.
This would have created an instance of the function that holds all of the information needed to call the fooFn method on the given object. You could then store the instance in a vector to call it at a later time (and had the same problem of making sure no boost::function bound to a destroyed object remains registered)
Edit:
For the sake of completeness, the link to the Boost bind documentation specific for binding members: http://www.boost.org/doc/libs/1_56_0/libs/bind/bind.html#with_member_pointers
What you are doing is actually quite similar only that you are now using a lambda to capture the object pointer and to define the function to be called.
So I see no problem with what you are doing (other then the one I already mentioned).
You could use an adapter class. This might be overkill for what you're doing, but it may work.
The benefits of doing it this way are:
You don't have to change the original classes. Creating void Foo::registerFnPointer() is ugly.
You don't have to use your static std::vector.
You don't have to deal with function pointers.
So let's say you have two different classes like this:
struct Foo
{
void fooFn () {
std::cout << "Foo::fooFn ()" "\n" ;
}
};
struct Bar
{
void barFn () {
std::cout << "Bar::barFn ()" "\n" ;
}
};
The goal is to put them into a container and call their respective *Fn () member-functions.
An adapter would look something like this:
struct Adapter_Base
{
virtual ~Adapter_Base () {} ;
virtual void adapterFn () = 0 ;
};
template <typename T>
struct Adapter : Adapter_Base
{
T tVal ;
Adapter (const T &tVal) : tVal (tVal) {}
void adapterFn () ;
};
template <>
void Adapter <Foo>::adapterFn ()
{
tVal.fooFn () ;
}
template <>
void Adapter <Bar>::adapterFn ()
{
tVal.barFn () ;
}
And you could use it like this:
int main ()
{
std::vector <std::unique_ptr <Adapter_Base> > v1 ;
std::unique_ptr <Adapter_Base> u1 (new Adapter <Foo> (Foo ())) ;
std::unique_ptr <Adapter_Base> u2 (new Adapter <Bar> (Bar ())) ;
v1.push_back (std::move (u1)) ;
v1.push_back (std::move (u2)) ;
for (auto &adapter : v1) {
adapter->adapterFn () ;
}
return 0 ;
}
Say i have the following class :
class A
{
public:
A() {
}
A(int a):_a(a){
}
int _a;
};
And the following function :
void someFunc (A a)
{
cout << a._a;
}
So the following line in the program works fine :
someFunc (5); // Calls A(int a) Constructor.
But the following does not :
someFunc(); //Compile error
One can expect that if it can build A when getting an integer,
why not build one using the default constructor as well, when called with no arguments?
Because someFunc() requires an argument and you have not provided an overload which does not. An implicit conversion from int to A exists, but that doesn't mean you can just ignore the function's signature and call it with no arguments. If you would like to call it with no arguments them assign a default value to a.
void someFunc(A a = A()) {
/* stuff */
}
Because you didn't call the function with an argument that turned out to be convertible, you called the function with no arguments. That's a different overload, one you haven't provided.
Consider these options:
Call the function like this: someFunc(A()).
Define a default value for the function parameter: void someFunc (A a = A()) { ... }.
Provide the no-argument overload: void someFunc() { someFunc(A()); }
This is because the signature of someFunc() does not match that of void someFunc (A a).
According to C++ standard, Section 13.3.2.3:
First, to be a viable function, a candidate function shall have enough parameters to agree in number with the arguments in the list.
A candidate function having more than m parameters is viable only if the (m+1)-st parameter has a default argument
None of this applies in this case, so void someFunc (A a) is not considered viable for the invocation with an empty parameter list.
Nitpick. From the 2003 C++ Standard,
17.4.3.2.1 Global names - ...
- Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace
I would tell you that it's poor practice to start any variable name with _. Especially as you may extend that practice into named variable arguments (int foo(int _a)), or do it with camelcase without thinking (int _MyVar). I personally do things like
int a_;
Will you ever actually have trouble? Probably not. But it's good practice not to start your anything with an underscore. Never with two underscores anywhere in the name, or started by an underscore followed by an uppercase letter, of course, too.
I'm not really providing an answer here, but it's useful information all the same... There are times when you really don't want to allow someFunc(5) to work, because it might lead to incorrect operation, or simply be misleading. In such cases you can declare the constructor as explicit:
class A
{
public:
A() {} // Are you sure you don't want to initialise _a here?
explicit A(int a) :_a(a) {}
int _a;
};
And as others have already said you can specify a default parameter for someFunc:
void someFunc( A a = A() );
Now:
someFunc(); // Calls A() by default
someFunc(5); // Not allowed because of implicit construction
someFunc(A(5)); // Caller must pass an instance of A
I am doing Box2D programming, and heads up, I am a total noob to C++ and C. I am an Objective-C guy, and that is why it is becoming really hard for me to understand the language. Especially:
->
Basically I understand that this is used for referencing different methods or functions or variables/properties like below:
body->GetWorld()->DestroyBody(body);
So is this equivalent to dot notation in Objective-C:
// made up example
[body.world destroyBody];
or
[self destroyBody:body.world];
Or something similar? I really don't understand this. Can someone give me a heads up on what this is. Thanks!
I don't know Objective-C, but I can explain difference between -> and . in C and C++, hope that helps.
. is operator that allows you to access member of struct/class instance. a->b is the same as (*a).b - so it first dereferences the pointer, then accesses member of instance that the pointer was pointing to.
Also, there is a case that Luchian has mentioned - overloading of operator->() of given class. In case when class you are using does overload this operator, the behavior will be different, defined by the class - it can return virtually everything it wants.
I don't know much about Objective-C, but I can try to give you some help about C++: assuming that you define a class Foo in C++, with a method bar():
class Foo
{
public:
void bar();
...
};
If you allocate an instance of Foo on the stack, you use dot notation (.) to call the method bar():
Foo f;
f.bar();
If you have a pointer to an instance of Foo, you use the arrow notation (->) to call the method bar():
Foo* pf; // must point to some instance of Foo
pf->bar();
(To complicate things, there are also references, which have value syntax and pointer semantics: if you have a reference to Foo (e.g. Foo& f) you still use dot notation: f.bar();.)
. is used to access object members, -> is used to access members through a pointer. Usually. operator -> can be overloaded, meaning you can also use it on objects:
struct X
{
X* other;
X* operator->() {return other;}
};
X x;
x->other;
In this case, x->other doesn't reffer to x.other, but to x.other.other. :D
No, using . to access Objective-C properties is not the same as either -> or . to access struct and class members in C and C++.
The Objective-C property accessor works on values of type id (which is a pointer type), but uses special naming conventions to decide what it actually does. It can directly access a property data member, making it similar to -> for data member access. Or it can look up special functions for getting and/or setting the property value, in which case it's syntax sugar for a message send.
Except in the case of operator overloading in C++, -> is always the same as dereferencing a pointer and then accessing the member referred to. a->b is equivalent to (*a).b. b may be a data member for a member function, but the accessed member will have the exact name referred to in b, not some mutation of it based on any special naming convention. If b names a member function then it may be a virtual function, which has some similarities to, but is not the same as, message sends in Objective-C. b may also be an overloaded member function in C++ which has no equivalent in Objective-C.
The addition of the . syntax for accessing object properties in Objective-C violates Objective-C's design principal that new features should look new. Using #, the [] message sending syntax, and the special keywords to define Objective-C objects are examples where Objective-C previously followed this design principal.
This is objective-c code.
#interface Foo : NSObject
{
NSInteger _a;
}
#property (nonatomaic, assign) NSInteger a;
#end
#implement Foo
#synthesize a = _a;
#end
You know '#synthesize' phrase.
#synthesize create bellow codes.
- (NSInteger)a
{
return _a;
}
- (void)setA:(NSInteger)aa
{
return _a = aa;
}
Let's access property a.
void main()
{
Foo foo = [[Foo alloc] init];
foo.a = 1;
}
Must assigned foo.a as 1.
But compiler call as bellow.
void main()
{
Foo foo = [[Foo alloc] init];
[foo setA:1];
}
foo.a = 1 and [foo setA:1] is same.
foo.a = 1 calls [foo setA:1].
Bellow, Written in C.
class Foo
{
private:
int _a;
public:
int getA();
void setA(const int aa);
};
int Foo::getA()
{
return _a;
}
void Foo::setA(const int aa)
{
_a = aa;
}
// local allocation example.
void main()
{
Foo foo;
foo.setA(1);
}
// Heap allocation example.
void main()
{
Foo *foo = new Foo();
foo->setA(1);
delete foo;
}
// Pointer (like object objectve-c).
void main()
{
Foo foo1;
foo1.setA(1);
Foo *foo2 = &foo1;
foo2->setA(2);
printf("result>>> %d, %d", foo1.a, foo2->a);
}
result>>> 2, 2
foo1.a and foo2->a is 2 also.
Objectve-C example bellow.
void main()
{
Foo *foo1 = [[Foo alloc] init];
foo1.a = 1;
Foo *foo2 = foo1;
foo2.a = 2;
NSLog(#"result>>> %d, %d", foo1.a, foo2.a);
}
result>>> 2, 2
Have a good day.
Thank you.
Given the following code:
#pragma once
class B
{
public:
B(void)
{
}
~B(void)
{
}
};
I know I can also write this:
#pragma once
class B
{
public:
B()
{
}
~B()
{
}
};
What is the purpose of having void in the first example? Is it some type of practice that states the constructor take zero parameters?
The two are same, at least in C++. In C, providing an empty pair of parentheses typically means an unspecified parameter list (as opposed to an empty parameter list). C++ does not have this problem.
How can a correct answer get downvoted so many times? Yet another SO bug?
A long time ago you did something like this in C (my pre-ISO C is rusty :) ):
void foo(a, b)
int a,
int b
{
}
while C++ was being created the name mangling required the types of the arguments, so for C++ it was changed to:
void foo(int a, int b)
{
}
and this change was brought forward to C.
At this point, I believe to avoid breaking existing C code this:
void foo()
and this:
void foo(void)
meant two very different things, () means do not check for the argument number or type, and (void) means takes no arguments. For C++ () meaning not to check anything was not going to work so () and (void) mean the same thing in C++.
So, for C++ () and (void) were always the same thing.
At least that is how I remember it... :-)
afaik if you pass void into the constructor or any function as the argument it means that the function dosnt take any argument so example a and b are equal. but i am not sure if any of them change the function signature in any way or make it run faster etc.
I just wanted to add that when you use void after the parameters like function():void it is used to indicate that the function does not return a value.