是否可以使函数接受给定参数的多种数据类型

is it possible to make function that will accept multiple data types for given argument?

本文关键字:参数 数据类型 可以使 函数 是否      更新时间:2023-10-16

编写函数 我必须声明输入和输出数据类型,如下所示:

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/