写一个函数我必须像这样声明输入和输出数据类型:
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/