C++ 是否有可能使函数接受给定参数的多种数据类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8627625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
is it possible to make function that will accept multiple data types for given argument?
提问by rsk82
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 ?
是否可以声明我的函数将接受 int、bool 或 char 类型的变量,并且可以输出这些数据类型?
//non working example
[int bool char] my_function ([int bool char] argument) {}
回答by parapura rajkumar
Your choices are
您的选择是
ALTERNATIVE 1
备选方案 1
You can use templates
您可以使用模板
template <typename T>
T myfunction( T t )
{
return t + t;
}
ALTERNATIVE 2
备选方案 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.
您为您期望的每个参数的每种类型提供不同的函数。您可以混合使用替代方案 1。编译器将为您提供合适的选择。
ALTERNATIVE 3
备选方案 3
You can use union
你可以使用联合
union myunion
{
int i;
char c;
bool b;
};
myunion my_function( myunion u )
{
}
ALTERNATIVE 4
备选方案 4
You can use polymorphism. Might be an overkill for int , char , bool but useful for more complex class types.
您可以使用多态。对于 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();
}
回答by stefanB
#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;
}
output:
输出:
33
a
1
Or you can do:
或者你可以这样做:
int i = f(33);
char c = f('a');
bool b = f(true);
回答by Andrew Marshall
回答by Kashif Khan
read this tutorial, it gives some nice examples http://www.cplusplus.com/doc/tutorial/templates/
阅读本教程,它给出了一些很好的例子http://www.cplusplus.com/doc/tutorial/templates/