Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to make function that will accept multiple data types for given argument?

Tags:

Writing a function I must declare input and output data types like this:

int my_function (int argument) {} 

Is it possible to make such a declaration that my function would accept variable of type int, bool or char, and can output these data types ?

//non working example [int bool char] my_function ([int bool char] argument) {} 
like image 887
rsk82 Avatar asked Dec 25 '11 00:12

rsk82


People also ask

Can a function have different data types?

Remember that function is a first-class data type in StreamBase. Therefore, anything you can do with a value of any data type you can do with function .

What makes it possible to use one function or class to handle many different data types?

Explanation: The function overloading is multiple functions with similar or different functionality but generic class functions perform the same task on given different types of data.

Which data types can be passed as an argument of a function?

An argument refers to values that are passed within a function when the calling of a function takes place. Furthermore, specifying argument data types is important for C++ programming. Moreover, C++ supports three types of argument data types – pass by value, pass by reference, and pass by pointer.


1 Answers

Your choices are

ALTERNATIVE 1

You can use templates

template <typename T>  T myfunction( T t ) {     return t + t; } 

ALTERNATIVE 2

Plain function overloading

bool myfunction(bool b ) { }  int myfunction(int i ) { } 

You provide a different function for each type of each argument you expect. You can mix it Alternative 1. The compiler will the right one for you.

ALTERNATIVE 3

You can use union

union myunion {      int i;     char c;     bool b; };  myunion my_function( myunion u )  { } 

ALTERNATIVE 4

You can use polymorphism. Might be an overkill for int , char , bool but useful for more complex class types.

class BaseType { public:     virtual BaseType*  myfunction() = 0;     virtual ~BaseType() {} };  class IntType : public BaseType {     int X;     BaseType*  myfunction(); };  class BoolType  : public BaseType {     bool b;     BaseType*  myfunction(); };  class CharType : public BaseType {     char c;     BaseType*  myfunction(); };  BaseType*  myfunction(BaseType* b) {     //will do the right thing based on the type of b     return b->myfunction(); } 
like image 100
parapura rajkumar Avatar answered Oct 10 '22 20:10

parapura rajkumar