c – 是否可以产生接受给定参数的多种数据类型的函数?

编写函数我必须声明输入和输出数据类型,如下所示:
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();
}

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...