0

I have a situation where a function can only take "int" (can't change this) and I need it in a different situation. let me directly write the code

bool foo(int dev) 
{
         ...
         ...
      return true/false;
}

I need to pass :

  1. mClassPointer->dev()
  2. mClassPointer[index]->dev()
  3. dev() //(function)
  4. and obviously dev //(variable)

mClassPointer is pointer to class. dev() is a member function of a class , return an Integer.

stinky472
  • 6,737
  • 28
  • 27
Select Call
  • 45
  • 1
  • 9

2 Answers2

1

You may be able to do that by changing the argument to a void*.

Be very careful with this and read this thread carefully, espc. the post by Loki Astari:

error: cast from 'void*' to 'int' loses precision

If the function only accepts an int then I don't know if this is possible. Read a discussion in this thread if you are thinking of casting your pointers to int and passing. May not work on certain platforms: Converting a pointer into an integer

Community
  • 1
  • 1
Sid
  • 7,511
  • 2
  • 28
  • 41
1

If you have a function that needs to handle different datatypes in different situations (as is vaguely implied in your question), then perhaps you need to look into templates.

Alex Z
  • 2,500
  • 2
  • 19
  • 23
  • +1 for how to make the function really generic. I don't really know if that's what he meant or if there's some weird restriction that only allows him to accept integers. – stinky472 Mar 02 '12 at 03:29
  • Please elaborate I have a situation where I can take only "int" value – Select Call Mar 02 '12 at 03:34
  • @SelectCall Could you elaborate as to your question? We're not sure what you want to do or why. – stinky472 Mar 02 '12 at 03:38
  • @SelectCall What other *types* do you want the function to take? Your question isn't clear enough there. Theoretically using a template can allow any type to be used... provided it doesn't break the code the template is used in – Alex Z Mar 02 '12 at 03:40
  • I have couple of device which I need to support , to validate the device I have been calling function at different places which takes above listed arguments . till now It has only "int" now as I am modifying further requires it to handle all I wanna make function generic – Select Call Mar 02 '12 at 03:48
  • If you want to employ generic functions while staying strictly C++, then templates are a much safer bet over using a void*. I'd suggest you follow the link I provided and learn about them. – Alex Z Mar 02 '12 at 03:57
  • Alex, can we have other option to do the same thing or other proposal for new funcation? – Select Call Mar 02 '12 at 04:23
  • Sorry, not sure what you mean there...could you elaborate? – Alex Z Mar 02 '12 at 04:28