Function with variable arguments

What disadvantages may arise if I want to use the function

foo(int num, ...)

to implement a variable number of arguments?

I know the first drawback is that you can use only one data type.

Is there any way to do this?

+3
source share
7 answers

There are several ways to NOT use ellipsis.

Why? Due to security types dangerous manipulation primitives ( va_start, va_arg, va_next), you can not send another function, etc.

However, contrary to C, C ++ provides template methods that offer a type of security and general behavior, and this can be accumulated with overloads:

template <typename Arg0>
void foo(int num, Arg0 const& arg0);

template <typename Arg0, typename Arg1>
void foo(int num, Arg0 const& arg0, Arg1 const& arg1);

// ... etc

, ( Boost.Preprocessor).

++ 0x , , C, (yeeha)

template <typename Arg0, typename... Args>
void foo(Arg0 arg0, Args... args)
{
  // Do something with arg0
  foo(args);
}

template <typename Arg0>
void foo(Arg0 arg0)
{
  // Do something with arg0
}

tuple:)

+2

; printf() C ( ++) .

, ; , . ( Go , - .)

- , . printf() , , . , ( ). - , . - - , vector<T> - . - - - .

, . , , .

+7

. . - . , . , . , . , , . , .

++ , , . . . - ++ iostreams, printf() C:

std::cout << 'I' << " love h" << 3 << "r\n";

, ++.

+4
void myprintf(char* fmt, ...)
{
    va_list args;
    va_start(args,fmt);
    vprintf(fmt,args);
    va_end(args);
}

int _tmain(int argc, _TCHAR* argv[])
{
    int a = 9;
    int b = 10;
    char v = 'C'; 
    myprintf("This is a number: %d and \nthis is a character: %c and \n another number: %d\n",a, v, b);
    return 0;
}
0

++

foo(blah, ArgList(a)(b)(c));

ArgList - , operator (), foo - , ArgList. . , .

Or something like

foo(blah)(a)(b)(c);

where foo is the overloaded class operator (). Here you create a temporary one, and the destructor will be called after the semicolon.

0
source

You can use the Loki Functor Library, which uses a list of types for a variable number of arguments for a function that is also type safe.

0
source

In addition to the type safety issues already raised, you cannot pass non-POD types like vararg in general.

0
source

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


All Articles