有没有可能编写一个函数,可以为给定的参数接受多个数据类型?

32

编写函数时,我必须像这样声明输入和输出数据类型:

int my_function (int argument) {}

是否有可能声明一个函数,它可以接受 int、bool 或 char 类型的变量,并能输出这些数据类型?

//non working example
[int bool char] my_function ([int bool char] argument) {}

2
你需要研究模板。 - Kashif Khan
6
它被称为“模板”(templates)。 - Sergio Tulentsev
1
@SergioTulentsev 你的链接显示403错误。 - Mia
2
@pkqxdd:是的,有时候链接会失效。不过,你可以在谷歌上搜索“c++模板”,然后选择前几个链接之一。今天是这个链接:http://www.cplusplus.com/doc/oldtutorial/templates/。 - Sergio Tulentsev
4个回答

50
你有两个选择:

方案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();
}

2
为什么不添加boost::any、void*和boost::variant呢?干脆一点走到底。 - user406009
1
@EthanSteinberg 请随意编辑答案... 我通常喜欢坚持使用标准的C++。 - parapura rajkumar
Op要求返回与参数相同的类型,而不是每次都返回int - Julien-L

8
#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);

@Rhexis,在这种情况下,它隐含地推断出“typename T”的值,基于函数“f()”的参数类型。 - Alberto Schiabel

4
使用一个模板(template):
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) { ... }

1

4
虽然理论上这段回答可以解决问题,但最好包含回答的关键部分并在此处提供链接以供参考。 - CodeMouse92

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接