is it possible to make function that will accept multiple data types for given argument?(是否有可能使函数接受给定参数的多种数据类型?)
问题描述
编写函数时,我必须像这样声明输入和输出数据类型:
Writing a function I must declare input and output data types like this:
int my_function (int argument) {}
是否可以声明我的函数接受 int、bool 或 char 类型的变量,并且可以输出这些数据类型?
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) {}
推荐答案
您的选择是
备选方案 1
您可以使用模板
template <typename T>
T myfunction( T t )
{
return t + t;
}
备选方案 2
普通函数重载
bool myfunction(bool b )
{
}
int myfunction(int i )
{
}
您为您期望的每个参数的每种类型提供不同的函数.您可以混合使用替代方案 1.编译器会为您选择合适的方案.
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.
替代方案 3
你可以使用联合
union myunion
{
int i;
char c;
bool b;
};
myunion my_function( myunion u )
{
}
替代方案 4
你可以使用多态.对于 int 、 char 、 bool 可能有点矫枉过正,但对于更复杂的类类型很有用.
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();
}
这篇关于是否有可能使函数接受给定参数的多种数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否有可能使函数接受给定参数的多种数据类型
基础教程推荐
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
