Difference between variable length argument and function overload

This question in C ++ seems pretty simple and general, but still I want someone to answer.

1) What is the difference between a function with a variable length argument and an overloaded function? 2) Will we have problems if we have a function with a variable-length argument and another function with similar arguments?

+3
source share
4 answers

2) Do you mean the following?

int mul(int a, int b);
int mul(int n, ...);

, 2 . n , var-args. f(1, 2) , , "", . . , , , :)


, . , .

int mul(int a, int b);
int mul(double a, ...);

, , , 0.0.

mul(3.14, 0.0); 

, , . , , . "" , .

+7

1) HELL . .
2) , , , . . , .

+1

, , .

. - , "" ( va_arg()), (.. , ). " " ( printf(), scanf()) " " ( , , ).

, - ++. - ++, , , , ++ (, "<" " → " )

class MyClass {
    public:
        MyClass & operator<<( int i )
        {
            // do something with integer
            return *this;
        }

        MyClass & operator<<( double d )
        {
            // do something with float
            return *this;
        }
};

int main()
{
    MyClass foo;
    foo << 42 << 3.14 << 0.1234 << 23;
    return 0;
}
+1

, . :

1) undefined, , POD. .

2) , . , . .

The first point - really serious - for most practical purposes, it displays lists of variable arguments solely as an "obsolete" element in C ++, and not to even consider using it in any new code. The most common alternative is a chain of overloaded operators (e.g. iostream and printf / scanf inserts / extractors).

0
source

Source: https://habr.com/ru/post/1720083/


All Articles