問題描述
編寫函數時,我必須像這樣聲明輸入和輸出數據類型:
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();
}
這篇關于是否有可能使函數接受給定參數的多種數據類型?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!