【问题标题】:is it possible to make function that will accept multiple data types for given argument?是否有可能使函数接受给定参数的多种数据类型?
【发布时间】:2012-01-27 11:54:55
【问题描述】:

写一个函数我必须像这样声明输入和输出数据类型:

int my_function (int argument) {}

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

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

【问题讨论】:

  • 你需要查看模板
  • 它叫templates
  • @SergioTulentsev 您的链接出现 403 错误
  • @pkqxdd:是的,有时链接会死掉。无论如何,您可以在谷歌上搜索“c++ 模板”并选择前几个链接中的一个。今天是this

标签: c++ function variables types


【解决方案1】:

你的选择是

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

【讨论】:

  • 为什么不添加 boost::any、void* 和 boost::variant?还不如全力以赴。
  • @EthanSteinberg 请随时编辑答案...我通常喜欢坚持标准 C++
  • Op 要求返回与参数相同的类型,而不是每次都返回 int
【解决方案2】:
#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);

【讨论】:

  • @Rhesis,在这种情况下,它会根据函数“f()”的参数类型隐式推断“typename T”的值
【解决方案3】:

使用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) { ... }

【讨论】:

    【解决方案4】:

    阅读本教程,它提供了一些很好的例子http://www.cplusplus.com/doc/tutorial/templates/

    【讨论】:

    • 虽然理论上可以回答这个问题,it would be preferable 在这里包含答案的基本部分,并提供链接以供参考。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 2020-12-26
    • 2016-02-29
    • 2022-06-14
    • 2018-12-30
    • 1970-01-01
    • 2017-09-28
    相关资源
    最近更新 更多