Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

c++ - is it possible to make function that will accept multiple data types for given argument?

Writing a function I must declare input and output data types like this:

int my_function (int argument) {}

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) {}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your choices are

ALTERNATIVE 1

You can use templates

template <typename T> 
T myfunction( T t )
{
    return t + t;
}

ALTERNATIVE 2

Plain function overloading

bool myfunction(bool b )
{
}

int myfunction(int i )
{
}

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.

ALTERNATIVE 3

You can use union

union myunion
{ 
    int i;
    char c;
    bool b;
};

myunion my_function( myunion u ) 
{
}

ALTERNATIVE 4

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...