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

C++ 是否可以使函数接受给定参数的多种数据类型?,c++,function,variables,types,C++,Function,Variables,Types,编写函数时,我必须声明如下输入和输出数据类型: int my_function (int argument) {} 是否可以声明我的函数将接受int、bool或char类型的变量,并可以输出这些数据类型 //non working example [int bool char] my_function ([int bool char] argument) {} 阅读本教程,它给出了一些很好的示例使用: 你的选择是 备选方案1 您可以使用模板 template <typename T&g

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

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;
}
对于所需的每种参数类型,都提供了不同的函数。您可以将其与备选方案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 i = f(33);
char c = f('a');
bool b = f(true);

你需要查看模板名为@SergioTulentsev的链接给出403error@pkqxdd:是的,有时候链接会死。不管怎样,你可以在谷歌上搜索“c++模板”,然后从前几个链接中选择一个。今天是。为什么不添加boost::any、void*和boost::variant呢?不妨全力以赴。@EthanSteinberg请随意编辑答案。。。我通常喜欢使用标准的C++Op asks来返回与参数相同的类型,而不是每次都返回
int
,虽然这可以从理论上回答问题,但在这里包含答案的基本部分,并提供链接以供参考。@Rhexis,在本例中,它根据函数“f()”的参数是什么类型隐式推断“typename T”的值
union myunion
{ 
    int i;
    char c;
    bool b;
};

myunion my_function( myunion u ) 
{
}
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);