C ++ variable number of arguments

I need to define a virtual function that can take a variable number of arguments, the problem is that c style ellipses do not work for non pod types, I have a limited amount of memory (2 KB), so I try to avoid allocating a temporary object just to go to the function all arguments will be of the same type (user-shared pointer), I also do not have access to stl or boost. Is there a C ++ trick that would allow me to call func with variable arguments?

+5
source share
5 answers

Assuming your argument types have a class Arg, you can try the following:

class ArgUser {
public:
    // syntactic sugar:
    void method() { // nullary
        doMethod();
    }
    void method( const Arg & a1 ) { // unary
        doMethod( &a1 );
    }
    void method( const Arg & a1, const Arg & a2 ) { // binary
        doMethod( &a1, &a2 );
    }
    // and so on, until max arity
private:
    // actual virtual function:
    virtual void doMethod( const Arg * a1=0, const Arg * a2=0 /*etc, until max arity */ ) = 0;
};

This solution has the following properties:

  • NVI
  • , , .
  • (inline).

( ) :

class AltArgUser {
public:
    // syntactic sugar:
    void method() { // nullary
        doMethod( 0, 0 );
    }
    void method( const Arg & a1 ) { // unary
        doMethod( &&a1, 1 );
    }
    void method( const Arg & a1, const Arg & a2 ) { // binary
        const Arg * args[] = { &a1, &a2 };
        doMethod( args, 2 );
    }
    // and so on, until max arity
private:
    // actual virtual function:
    virtual void doMethod( const Arg * args[], size_t numArgs ) = 0;
};

, , , . , , .

+4

, .

, , alloca free.

+2

- POD, , ? ( ):

shared_ptr arg1;
shared_ptr arg2;

ClassWithVirtualFunction c;

c.yourVirtualFunction(&arg1, &arg2, NULL);

ClassWithVirtualFunction
{
    virtual void yourVirtualFunction(shared_ptr* first, ...)
    {
        va_list marker;

        va_start( marker, first );

        shared_ptr* current=first;

        while (current != NULL)
        {
            /* do stuff with *current */
            current = va_arg( marker, shared_ptr* );
        }
        va_end(marker);
    }
}
+1

, , . .

mytype arr[3];
arr[0] = a;
// etc
myfunction(arr, 3);
0

, , (, , ++), " " NULL, .

- :

class MyPointer
{
  // Whatever you have/want
};

class MyArgs
{
  static int nargs; // Static class variable for total number of args
  MyPointer* data;
  MyArgs*    next; 

  public:
  MyArgs(int nargs)
  {  
    // Some funky constructor to create required number of args...
  }  

  MyPointer* operator[](int at)
  {  
    // Nice overloaded operator for you to get at data
  }  

};

class PlanToDoStuff
{
  public:
  virtual void foobar(MyArgs)=0;
};

class ActuallyDoStuff: public PlanToDoStuff
{
  public:
  void foobar(MyArgs)
  {  
    // Do stuff with args...
  }  
};

int main()
{
    MyArgs args(3);
    ActuallyDoStuff dosomething;
    dosomething.foobar(args);

}
0
source

All Articles