void f2(int& i)
{
}
void f1(int& j)
{
f2(j);
}
int main()
{
int k;
f1(k);
}
If you can't reference a reference, why does this compile?
Quote:Original post by thedevdan
Then how do you get a reference to reference another one?
You can't (at least not legally). If you want this concept use a reference to a pointer or a pointer to a pointer instead.
OH!
I had always head that you can't do reference a reference, and that it was a problem. Now I see that what those people were really trying to do was change the second reference to reference something else.
Good, because after I read that I was wondering why all of my code ever compiled when I have several reference "layers" like I showed. Thanks a lot!
I had always head that you can't do reference a reference, and that it was a problem. Now I see that what those people were really trying to do was change the second reference to reference something else.
Good, because after I read that I was wondering why all of my code ever compiled when I have several reference "layers" like I showed. Thanks a lot!
The thing you have to remember is that a reference is basically an alias to the storage location. It's basically just adding another name to that variable, it's not really creating a new variable.
This would be what you are thinking of...
error C2528: '<Unknown>' : pointer to reference is illegal
'nuf said!
void f2(int&* i){}void f1(int& j){ f2(&j);}int main(){ int k; f1(k);}
error C2528: '<Unknown>' : pointer to reference is illegal
'nuf said!
typedef int& IntRef;//You can't take a reference to an IntRef.int n = 5;IntRef ref = n;IntRef& rref = ref; //not allowed
This kind of problem crops up, usually in template programming, where you don't know what types you are going to get given.
//general class to make a reference typetemplate<typename T>struct Ref { typedef T& type;};//specialisation if the type is already a referencestruct <typename T&> Ref { typedef T& type;};int main() { int n = 5; double d = 3.142; Ref<int>::type nref = n; Ref<double>::type dref = d; typedef int& IntRef; Ref<IntRef>::type nrefRef = n; return 0;
Not checked but I think that's right.
edit: yep, made a mistake
[Edited by - petewood on September 23, 2004 8:36:34 AM]
Quote:Original post by petewood
*** Source Snippet Removed ***
This kind of problem crops up, usually in template programming, where you don't know what types you are going to get given.
*** Source Snippet Removed ***
Not checked but I think that's right.
I don't think your reference sytax is correct:
It's type& variable = othervariable, not type variable& = &othervariable. Notice the lack of the second &. Actually, your way might be another syntax, but I doubt it. If it is, yell at me.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement