是否可以使函数接受给定参数的多个数据类型? [英] is it possible to make function that will accept multiple data types for given argument?

查看:161
本文介绍了是否可以使函数接受给定参数的多个数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写函数我必须声明这样的输入和输出数据类型:

  int my_function(int argument){} 

可以声明我的函数接受int,bool或char类型的变量,并且可以输出这些数据类型?

  //非工作示例
[int bool char] my_function char] argument){}


解决方案

p>

替代1



您可以使用范本

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

ALTERNATIVE 2



平原函数重载

  bool myfunction(bool b)
{
}

int myfunction(int i)
{
}


$ b b

您为每个期望的每个参数提供不同的函数。



ALTERNATIVE 3



您可以使用union

  union myunion 
{
int i;
char c;
bool b;
};

myunion my_function(myunion u)
{
}

ALTERNATIVE 4



您可以使用多态性。

  class BaseType 
{
public:
virtual BaseType * myfunction()= 0;
virtual〜BaseType(){}
};

类IntType:public BaseType
{
int X;
BaseType * myfunction();
};

类BoolType:public BaseType
{
bool b;
BaseType * myfunction();
};

class CharType:public BaseType
{
char c;
BaseType * myfunction();
};

BaseType * myfunction(BaseType * b)
{
//将根据b类型执行正确的操作
return b-> myfunction ;
}


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) {}

解决方案

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

这篇关于是否可以使函数接受给定参数的多个数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆