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

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

关于c++ - 是否有可能使函数接受给定参数的多种数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8627625/

相关文章:

c++ - 遍历字符串会导致段错误

c++ - 在 C++ 中制作 3d 文本编辑器

c++ - 为什么下面的程序运行良好?我从函数返回对局部变量的引用

function - MIPS 中的函数(过程)

javascript - 将 2 个 JavaScript 变量的内容交换为另一个

c++ - 为英特尔 C++ Composer "GCC not found"设置环境变量时出现问题

c++ - 如何同时使用两个CameraCaptureUI(UWP/C++)

c++ - 为什么 C++ 允许将指向基对象的指针转换为派生类的指针

javascript - 如何测试传递给函数的元素是否是文档本身?

php - htaccess 命令只允许来自同一服务器的请求(不指定 IP)