Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

johnnyBravo

Some way of making a function accept any data type?

This topic is 5406 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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,

Share this post


Link to post
Share on other sites
Advertisement
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(...);

Share this post


Link to post
Share on other sites
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


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]

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!