-
July 7th, 2009, 10:13 AM
#1
How to define a method with a generic parameter
Hello everyone !
I think i've solved the problem.
like this :
Code:
template <class myType>
void TestEmpty(myType object);
I want to implement my own exception class, and i need to define a method with a generic parameter.
something like this:
Code:
void Test_Empty(T object) {
if (obj==NULL) /* the object type is unknown at compilation time*/
cout<< "No data exception";
}
The problem is that I do not know how to define a default type parameter of my test function.
Once it can be of type int, other wise of type float for instance.
Can you please give me some suggestions.
Last edited by munteanu24d; July 7th, 2009 at 10:38 AM.
-
July 7th, 2009, 12:29 PM
#2
Re: How to define a method with a generic parameter
Templated functions cannot have default type arguments, however it is easily worked around by making your function a static member of a templated empty class which can have default type arguments.
Code:
template < typename T = int >
struct FuncHolder
{
static void TestEmpty( T obj )
{
// .....
}
};
At least i think thats what you meant.
Get Microsoft Visual C++ Express here or CodeBlocks here.
Get STLFilt here to radically improve error messages when using the STL.
Get these two can't live without C++ libraries, BOOST here and Loki here.
Check your code with the Comeau Compiler and FlexeLint for standards compliance and some subtle errors.
Always use [code] code tags [/code] to make code legible and preserve indentation.
Do not ask for help writing destructive software such as viruses, gamehacks, keyloggers and the suchlike.
-
July 7th, 2009, 12:59 PM
#3
Re: How to define a method with a generic parameter
Originally Posted by munteanu24d
The problem is that I do not know how to define a default type parameter of my test function.
Once it can be of type int, other wise of type float for instance.
Can you please give me some suggestions.
Default types do not make sense for functions. Your function will be called with an argument and the argument will definitely have a type, thus the default type will never come into play.
However it is not clear what you are trying to do. If you want your function to be called with int and float types you should not compare the argument with null. Comparing an int with null make little sense and comparing a float with null makes no sense.
So maybe you explain how you intend to use your function.
More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity. --W.A.Wulf
Premature optimization is the root of all evil --Donald E. Knuth
Please read Information on posting before posting, especially the info on using [code] tags.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|