Some way of making a function accept any data type?
Hi, im wondering if its possible to have a function accept any data type. eg
function(anyDataType value)
{
}
, that is without making lots of functions of the name with different datatypes.
Thanks,
Assuming C++, you can make it a template function and parameterize the function argument time. e.g.:
template <typename T>
void function(T value) {
}
Or, if you want to travel to the land of extremely bad ideas you can do:
void function(...);
template <typename T>
void function(T value) {
}
Or, if you want to travel to the land of extremely bad ideas you can do:
void function(...);
i want to do this because i am storing integers, floats etc into a file, and iam making a class wrapper over the fstream
one of the most basic and yet important features of c++ is function overloading
you can define multiple functions with the same name as long as they difer in parameters, you could have
and in your main...
int main()
{
int bleh = 21;
PrintStuff(bleh); // since bleh is an integer, the compiler knows to use the definition of PrintStuff, that has an integer for a param
return 0;
}
[edited by - Ademan555 on February 29, 2004 3:57:53 AM]
you can define multiple functions with the same name as long as they difer in parameters, you could have
void PrintStuff(char ch){std::cout<<"You passed "<<ch<<" ,which is a character, to the PrintStuff function\n";}void PrintStuff(int i){std::cout<<"You passed "<<i<<" ,which is an integer, to the PrintStuff function\n";}void PrintStuff(float fl){std::cout<<"You passed "<<fl<<" ,which is a float, to the PrintStuff function\n";}
and in your main...
int main()
{
int bleh = 21;
PrintStuff(bleh); // since bleh is an integer, the compiler knows to use the definition of PrintStuff, that has an integer for a param
return 0;
}
[edited by - Ademan555 on February 29, 2004 3:57:53 AM]
ya, i didnt want to use overloading, as i might want to use custom made classes, imso far using void *, but havent tested it on classes yet
template <typename T>void PrintStuff(T val){ std::cout << "You passed " << val << ", which is a " << typeid(T).name() << ", to the " << __FUNCTION__ << " function\n";}
__FUNCTION__ only works on ms compilers 7.0+ and I believe most versions of gcc
boost::any perhaps?
[How To Ask Questions|STL Programmer''s Guide|Bjarne FAQ|C++ FAQ Lite|C++ Reference|MSDN]
[How To Ask Questions|STL Programmer''s Guide|Bjarne FAQ|C++ FAQ Lite|C++ Reference|MSDN]
quote:Original post by dalleboy
boost::any perhaps?
.. which eventually drives you into lots of if-then statements
as you need to use boost::any_cast.
[edited by - darookie on February 29, 2004 6:43:58 AM]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement