是否可以使函数接受给定参数的多种数据类型
is it possible to make function that will accept multiple data types for given argument?
编写函数 我必须声明输入和输出数据类型,如下所示:
int my_function (int argument) {}
是否可以做出这样的声明,我的函数将接受 int、bool 或 char 类型的变量,并且可以输出这些数据类型?
//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。编译器将适合您。
备选案文3
您可以使用联合
union myunion
{
int i;
char c;
bool b;
};
myunion my_function( myunion u )
{
}
备选案文4
您可以使用多态性。对于int,char,bool来说可能有点矫枉过正,但对于更复杂的类类型很有用。
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();
}
#include <iostream>
template <typename T>
T f(T arg)
{
return arg;
}
int main()
{
std::cout << f(33) << std::endl;
std::cout << f('a') << std::endl;
std::cout << f(true) << std::endl;
}
输出:
33
a
1
或者你可以做:
int i = f(33);
char c = f('a');
bool b = f(true);
使用模板:
template <typename T>
T my_function(T arg) {
// Do stuff
}
int a = my_function<int>(4);
或者只是超载:
int my_function(int a) { ... }
char my_function(char a) { ... }
bool my_function(bool a) { ... }
阅读本教程,它给出了一些很好的例子 http://www.cplusplus.com/doc/tutorial/templates/
相关文章:
- 如何使用宏根据参数定义不同的数据类型?
- 参数数据类型未知的可变参数函数
- 为什么指定数据类型而不是构造功能参数?C
- 模板参数在具有相同数据类型的单个类型名的构造函数中不起作用
- 即使数据类型不同,是否有可能将帧的参数作为参数传递给回溯中的另一个帧
- 将任何数据类型/对象作为参数传递以确定其大小
- 我如何实现递归函数的模板,该模板允许C 中的许多不确定数据类型的参数
- 为什么C CHAR数据类型3D数组通过参数第一个括号为空白
- 根据参数设置构造函数的成员数据类型
- 具有不同数据类型或参数的不同函数的函数指针
- 以其数据类型作为参数以指针
- 函数有没有办法自动检测其参数的数据类型?(请不要建议函数重载)
- 使用两种数据类型作为参数堆叠STL
- 数据类型与模板参数不同的模板对象
- 具有指针数据类型的非类型函数模板参数
- C++指向函数作为参数的指针.数据类型不兼容
- 如何具有抽象数据类型的参数
- 将数据类型作为字符串放入模板参数中 - C++
- C++大小感知数据类型/参数
- PostgreSql查询参数数据类型错误