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

is it possible to make function that will accept multiple data types for given argument?(是否有可能使函数接受给定参数的多种数据类型?)
本文介绍了是否有可能使函数接受给定参数的多种数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

Writing a function I must declare input and output data types like this:

int my_function (int argument) {}

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

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 ?

//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.编译器会为您选择合适的方案.

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.

替代方案 3

你可以使用联合

union myunion
{ 
    int i;
    char c;
    bool b;
};

myunion my_function( myunion u ) 
{
}

替代方案 4

你可以使用多态.对于 int 、 char 、 bool 可能有点矫枉过正,但对于更复杂的类类型很有用.

You can use polymorphism. Might be an overkill for int , char , bool but useful for more complex class types.

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

这篇关于是否有可能使函数接受给定参数的多种数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)
STL BigInt class implementation(STL BigInt 类实现)
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)