문제

In Objective-C you can say something like:

NSArray *anArray = [NSArray arrayWithObjects:obj,obj2, nil];

In case you are not familiar with objective-c it is saying I want an object of type of NSArray, anArray, and I want to call the method arrayWithObjects and then it acts as a sentinel and accepts as many parameters (which in this case are objects) until it reaches nil.

Is there any way to achieve something like this:

createObjects(o1,o2,o3,o4,-1);

Where the method of function can accept as many parameters until it reaches some key value?

Now, I am aware you can do sentinel stuff in C and C++, but is there a way to provide something like this to a method like they do in Objective-C?

도움이 되었습니까?

해결책

You can write a variadic function and use a sentinel to locate the last real argument.

However, in C++, this is usually a bad idea because variadic functions are not type safe. It's preferred in C++ to put the elements you want to pass into a container, array, or class object of some kind and then pass that to the function. It's much less error-prone and much easier to verify.

다른 팁

I think what you are looking for is varargs.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top