简体   繁体   中英

C++ function parameters or parameter array

My background and instincts tell me I should always create a tighter and more explicit interface to a function by requiring parameters like this:

bool someFunc(int param1, int param2, char param3, float param4) {
   ...
}

or requiring an object (struct or class) like:

class someObject {
    ...
    int p1;
    int p2;
    char c1;
    float p4;
}

I have been told by my boss that I should be using something like:

bool someFunc(void *params[], int size) {
   ...
}

because it creates more extensible (you can iterate over parameters this way) and faster code.

I am only interested in improving my abilities, but my instincts go against this method. Is he right?

Horrible idea. I can't list the reasons why it's bad in a single answer, but the main problem is that it just doesn't work. As a simple example, you can't pass 3, and if you pass 0 it becomes a nullptr. More importantly, you have to cast the values back to a given type anyway, so why not specify the type in the signature?

Now there's a real C++ alternative, variadic templates:

template<typename... Arguments>
void Foo(Arguments... parameters);

In this case, the compiler will know all the types in Arguments... , there's no need to cast anything.

I disagree with the above answer, your instincts are right you should try and create a explicit interface to a function. There are times where you can't have an explicit interface, and then you should consider variadic template arguments, but they're rare. Two Ints a char and float seem like a perfectly reasonable function parameters.

However you're in a very sticky situation, you don't want to go against your boss. I would be skeptical of any programming advice from him, he's either not a very good programmer or worse one of those old school hacky c programmers (see if he uses MACROS everywhere). My advice is to do it his way now, then if you're ever working with that function again later fix it and try and get someone else to review your code.

Your boss is crazy. Such debauchery had some place in C, and even there you would use varargs , not this crazy construct. If you want to program in a dynamically-typed language, either don't use C++, or use arrays of variant types (say boost::variant or QVariant ).

The "extensibility" your boss is looking for and obviously missing is otherwise known as function/method overloading. It has its place as a part of a proper design, not as an edict.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM