编写函数时,我必须像这样声明输入和输出数据类型:
int my_function (int argument) {}
是否有可能声明一个函数,它可以接受 int、bool 或 char 类型的变量,并能输出这些数据类型?
//non working example
[int bool char] my_function ([int bool char] 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。
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();
}
int
。 - Julien-L#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/