-
Template exceptions
Hey everyone. I have a function, Add, in my class, VQueue, which is templated.
Code:
VQueue<MyStruct> MyQ;
Add takes one parameter: The address of a variable of the class's type.
Code:
template<class Type>
void VQueue<Type>::Add( Type& Addition ) { ... }
But when I make VQueue of type int...
[code]
VQueue<int> MyOtherQ;
[code]
and pass 5 to Add...
it says that there is no function that accepts type int. Well I understand that part, because it's an integer, and not the address of an integer. This would work fine:
Code:
int Moo = 5;
MyOtherQ.Add( Moo );
But I want to be able to just use 5 instead of making it another variable. I can't make Add accept the Type by value, because that would mean passing large structures by value.
So I had this crazy idea, "What if I use passing a reference for all the types except the simple ones (int, char, bool, int*, etc.)?"
How do I do this? I have no idea where to start. Or can someone give me a few keywords to search for? I tried "templated classes c++ exceptions" but all it gave me was try-throw-catch junk.
Thanks!
Thanks!
-
As you discovered, C++ views literals differently as they don't have addresses.
EDIT: Damn, that was stupid.
/me goes off to play with this, ignore the following as it doesn't work.
There must be an answer though, as the vector class takes variables or literals, and according to the SGI reference (and common sense) it uses pass by reference.
What you could do is just overload the template functions.
Code:
template<class Type>
void VQueue<Type>::Add( Type& Addition ) { ... }
template<class Type>
void VQueue<Type>::Add( Type Addition ) { ... }
Let me think about this...
I'm thinking that you shouldn't run into the problem you described very often though. You don't run into literals in (good) code very often, and in most cases it's fairly painless to move a literal into the appropriate type. The overloaded function would just do the job of copying the value for you (at which point you could call the function that takes a reference to do the heavy-lifting).
-
okay, a function uses pass by reference can handle a literal, but only if the parameter is constant .
I'm guessing that this shouldn't be a problem for an Add() function. The only time you'd need a non-constant pass by reference were if you were going to modify the parameter (ie use it as another return value), but that obviously wouldn't make sense for a literal, which can't be 'changed.'
Code:
#include <cstdlib>
// this works fine with anything
void foo(const int& bar)
{
int baz = bar;
}
// this will not work with a literal!
void pitythefoo(int& bar)
{
int baz = bar;
}
int main(int argc, char *argv[])
{
int var = 5;
foo(var);
foo(5);
system("PAUSE");
return EXIT_SUCCESS;
}
-
very very simple fix
Code:
void VQueue<Type>::Add(const Type& Addition ) { ... }
edit: don't forget to change the prototype too
-
IT WORKED! YES! Thank you so much!