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

前端 未结 4 651
广开言路
广开言路 2020-12-02 16:29

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 de

相关标签:
4条回答
  • 2020-12-02 16:37

    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();
    }
    
    0 讨论(0)
  • 2020-12-02 16:41

    read this tutorial, it gives some nice examples http://www.cplusplus.com/doc/tutorial/templates/

    0 讨论(0)
  • 2020-12-02 16:43
    #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;
    }
    

    output:

    33
    a
    1
    

    Or you can do:

    int i = f(33);
    char c = f('a');
    bool b = f(true);
    
    0 讨论(0)
  • 2020-12-02 16:49

    Use a template:

    template <typename T>
    T my_function(T arg) {
      // Do stuff
    }
    
    int a = my_function<int>(4);
    

    Or just overload:

    int my_function(int a) { ... }
    char my_function(char a) { ... }
    bool my_function(bool a) { ... }
    
    0 讨论(0)
提交回复
热议问题