How to Make Function That Will Accept Multiple Data Types for Given Argument

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

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();
}

How do you make a function accept multiple types?

You can use interface types as arguments, in which case you can call the function with any type that implements the given interface. In Go types automatically implement any interfaces if they have the interface's methods. So if you want to accept all possible types, you can use empty interface (interface{}) since all types implement that. No other modification needs to be done to your function.

func print_out_type(x interface{}) string {
switch v := x.(type) {
case string:
return "A string"
case int32:
return "An Integer"
default:
return "A default"
}
}

You can also use the reflect package to study the type of an interface variable. For Example:

func print_out_type(x interface{}) string {
return reflect.TypeOf(x).String()
}

func main() {
fmt.Println(print_out_type(42))
fmt.Println(print_out_type("foo"))
}

Will print

int

string

C multiple data types passed to the same function

You cannot use a single function for that, you need multiple functions.

Otherwise, accessing (*value) that is an integer pointer pointing to uint8_t object, i.e.

// This code is broken
unit8_t val = 0xC4;
change_nth_bit((int*)&val, 3, 1);
// ^^^^^^
// |
// Invalid ------+

would result in undefined behavior.

Note that if you put this code in a macro (after replacing a pointer with a macro parameter reference) you should be able to achieve the desired result without repeating your code:

#define CHANGE_NTH_BIT(v,b,n) (v) ^= (-(b) ^ (v)) & (1U << (n))

How can you write a function that accepts multiple types?

With autoboxing / autounboxing, you can do this:

public static void print(Object s) {
System.out.println(s.toString());
}

public static <T> void printArray(T[] arr) {
for (T t : arr) {
print(t);
}
}

The one drawback is that the argument to printArray must be an array of a reference type, but unlike the varargs solution this will work for any reference type.

Edit: regarding the varargs solution and @matthy's question about combining the two methods into one (ie generifying it), you could also do something like this:

static public <T> void print(T... ts) {
for (T t : ts) {
System.out.print(t + " ");
}
System.out.println("");
}

However, you still cannot call it on an array of primitives:

int[] x = { 1, 2 };
print(x);

Because Java takes T to be int[] and will execute the toString method of the array rather than iterate through the contents. If you call it on an array of Integer or other reference type then it will work also.

How do I specify multiple types for a parameter using type-hints?

You want a type union:

from typing import Union

def post_xml(data: Union[str, ET.Element]):
...

for python 3.10
PEP 604 was introduced and instead of:

def post_xml(data: Union[str, ET.Element]):

you can write the following

def post_xml(data: str | ET.Element):

Can you make a function accept two different data types?

Dart doesn't allow function/method overloading. You can either use different names for the methods or optional or named optional parameters to be able to use a method with different sets of parameters.

Allow Swift function parameter to be of multiple types

You mentioned enums, which sound like an excellent fit for this use case.
You can explicitly only require the types you expect, and nothing else.
By adding a property to the enum you can then expose a UIControl property to interact as needed, without the need for down-casting (which is generally considered to be an anti-pattern).

enum Component {
case `switch`(UISwitch)
case stepper(UIStepper)

var control: UIControl {
switch self {
case .switch(let comp):
return comp
case .stepper(let comp):
return comp
}
}
}

Then ask for a Component as a parameter to the function.

func controlValueChanged(_ myComponent: Component) {
// Now you can use them as a generic UIControl
let control = myComponent.control

// ...or different behaviours for each element
switch myComponent {
case .switch(let swit):
// use the `swit`
case .stepper(let step):
// use the `step`
}
}

Having said that, if the implementations for these types are totally different anyway, it may be more clear to define two separate functions.



Related Topics



Leave a reply



Submit