Optional parameter in C++ without overloading [duplicate] - c++

This question already has answers here:
What would be a proper invalid value for a pointer?
(7 answers)
Closed 7 years ago.
I'd like to have a function with an optional parameter but without overloading the function. The reason I don't want to overload is because the function body is quite long, and the version with the optional parameter just differs by a single line.
void myFunction(MyClass my_optional_arg = MyClass())
{
// lots of statements
if (optional_argument_was_passed)
doSomething(my_optional_arg);
// lots more statements
}
int main()
{
myFunction();
MyClass my_optional_object();
myFunction(my_optional_object);
}
The problem that I have with the default parameter route is that I don't know how to check whether the optional parameter was passed or not, i.e., I don't know how to set the boolean flag optional_argument_was_passed. For example, just testing equality of the parameter with the default isn't sufficient because that same default value could be passed into the function. What I'd really like is something like this:
void myFunction(MyClass my_optional_arg = some_unique_null_value)
{
// lots of statements
if (my_optional_arg != some_unique_null_value)
doSomething(my_optional_arg);
// lots more statements
}
It has been suggested that I do something like this:
void myFunction()
{
MyClass my_object();
myFunction(my_object);
}
However, this is not quite what I need; the myFunction(MyClass) function is not necessarily the ultimate function to be used. If I call the function without the optional argument, myFunction(), then I don't want any object of class MyClass to even enter the function at all; rather, the statement that uses this object, called doSomething(MyClass) above, should be omitted.
It has also been suggested that I remove the common parts of both functions to its own function myFunction() and then create an overloaded wrapper function to call the statements with the optional parameter:
void myFunction(MyClass my_optional_arg)
{
doSomething(my_optional_arg);
myFunction();
}
This is a solution, but it would be a bit messy because I have a lot of statements before AND after the doSomething(MyClass) call, so I'd need to split the function into several parts:
void myFunction(MyClass my_optional_arg)
{
myFunctionPartA();
doSomething(my_optional_arg);
myFunctionPartB();
}
void myFunctionPartA()
{
// lots of statements
}
void myFunctionPartB()
{
// lots more statements
}

if the functions are similar then call one from the other. OR have an internal 'do all the work and take all the paramters' function that all the overloads call. This is a very common tactic
void Func() // func with foo defaulting to 42
{
Func(42);
}
void Func(int foo)
{
// one million lines of code
}

Related

LevelDB --- Code in C++

The below given code is taken from LevelDB. I am giving two blocks of code for better understanding. I am unable to understand what is happening.
ThreadState is a structure and I have written here to make it easy for the reader.
struct ThreadState {
int tid; // 0..n-1 when running in n threads
Random rand; // Has different seeds for different threads
Stats stats;
SharedState* shared;
ThreadState(int index)
: tid(index),
rand(1000 + index) {
}
};
Is the marked code below an object instantiation of class Benchmark? What is happening in the marked code below?
void Run() {
PrintHeader();
Open();
const char* benchmarks = FLAGS_benchmarks;
while (benchmarks != NULL) {
{
//code ommitted
}
// Reset parameters that may be overriddden bwlow
***void (Benchmark::*method)(ThreadState*) = NULL;*** // What does this code line mean? // Benchmark is a class.
bool fresh_db = false;
int num_threads = FLAGS_threads;
if (name == Slice("fillseq")) {
fresh_db = true;
method = &Benchmark::WriteSeq;
}
If required, I can give detailed implementation of Benchmark as well.
Thanks a lot for the help!
void (Benchmark::*method)(ThreadState*) = NULL;
// What does this code line mean?
// Benchmark is a class.
The above is a pointer to a member function. Since member functions are not like regular functions (they can only be called on a valid object), you cannot take their address it the same way you would for a free function.
Therefore the above syntax is introduced. It is similar to a regular function pointer except the class specifier Benchmark::. This is essentially the type of the implicit this pointer.
In your case, method is a pointer to a member function that takes ThreadState* as a parameter, and has a void return type. The reason for using it is most probably to simplify the call. First, and based on various parameters, a member function is chosen to be called, and its "address" stored in method. After all the checks are done, there is only a single call to the chosen function via the pointer to member.
Incidentally, &Benchmark::WriteSeq is how the code obtains the "address" of the member function WriteSeq. You must use the address-of operator on the qualified function name.

c++: Not able to understand Message Handlers

Actually I am new to writing handlers but somehow i managed to write this piece of code:
#include<iostream>
using namespace std;
class test
{
public:
typedef void (test::*MsgHandler)(int handle);
test()
{
cout<<"costructor called"<<endl;
}
void Initialize()
{
add_msg_Handler(4,&test::System);
}
void System(int handle)
{
cout<<endl<<"Inside System()"<<endl;
cout<<"handle:"<<handle<<endl;
}
protected:
MsgHandler message[20];
void add_msg_Handler(int idx,MsgHandler handler)
{
cout<<endl<<"Inside add_msg_Handler()"<<endl;
cout<<"handler:"<<handler<<endl;
message[idx]=handler;
cout<<"message:"<<message[idx]<<endl;
}
};
int main()
{
test obj;
obj.Initialize();
return 0;
}
This code is working fine, I get the output as:
costructor called
Inside add_msg_Handler()
handler:1
message:1
But there are several things beyond my scope. If I am right System() should have been called in this line:
add_msg_Handler(4,&test::System);
but this is not happening. I need help on rectifying this.
Second thing is, I am not able to understand why I am getting such output:
handler:1
I mean how does handler got initialized to 1.Can somebody help me in solving this??
&test::System is not a function call, it's a pointer to the member function test::System.
(A call would look like System(0) and wouldn't compile if you used it as the parameter in question.)
If you look at the definition of add_msg_handler:
cout<<endl<<"Inside add_msg_Handler()"<<endl;
cout<<"handler:"<<handler<<endl;
message[idx]=handler;
cout<<"message:"<<message[idx]<<endl;
there's not a single place that calls the function handler.
(A call would look like (this->*handler)(0) or (this->*message[idx])(0).)
So the function isn't called because there's nothing in your code that calls it.
The output is 1 because
handler is a pointer to a member function
there's no overload of << for pointers to member functions
there is an implicit conversion from pointer to member function to bool
there's an overload of << for bool
a non-null pointer is implicitly converted to true
true outputs as 1 by default.

Unusual C++ function declaration

There are a few legal ways which can we declare a function in C++.
Some of the legal ways are:
void function ();
void function (void);
dataType function (dataType);
and so on...
Recently, I came across a function declaration as such:
void (function) (); //Take note of the braces around the function name
I have never seen somehting like this before, when I tested it in a C++ compiler, it runs without any warning or compilation errors.
My question is: Why is void (function) (); a legal way to decalre a function prototype? Is there any special meaning to declare a function in this way? Or does it just work normally like any other function declaration?
One difference is that enclosing it in parenthesis prevents the function-like macros expansion by the preprocessor. As mentioned in the other answers it makes no difference though to the actual compiler.
For instance:
// somewhere buried deep in a header
#define function(a, b) a + b
// your code
void function() { // this expands the macro and gives compilation error
}
void (function)() { // this does not expand and works as expected
}
This comes in handy for instance when the bright minds behind the Microsoft Visual Studio library decided to provide function-like macros for things like min and max. (There are other ways like #undef to go around this).
Note that object-like macros (e.g. #define function 3 + 4) are still expanded.
The preprocessor is just a dumb text replacement tool (as opposed to the compiler which is just a (smart) text replacement tool). It takes the macro definition and replaces it everywhere. He is not aware of the semantics of what he replaces.
For instance:
// somewhere buried deep in a header
#define function 3 + 2
// your code
void function() {
}
The preprocessor sees the word function and textually replaces it with the string 3 + 2. He is unaware that function is a id-name part of a function declaration and definition. After the preprocess phase there come the actual compile phases. So the compiler actually sees:
// your code
void 3 + 2() {
}
which does not make any sense to him and gives an error.
For function-like macros
// somewhere buried deep in a header
#define function(a, b) a + b
The preprocessor does the same except that it expects two ‘tokens’ enclosed in parenthesis separated by comma (the parameters) and does the replacement. (again no semantics aware):
int d = function(2, 3);
//will be replaced by the preprocessor to:
int d = 2 + 3; // passes compilation phase
void function();
// the preprocessor doesn’t find the arguments for function so it gives an error.
However if it encounters (function) it will not try to expand it (it ignores it). It is just a rule.
it's the same as
void function();
you can declare it as
void ((function)) ();
if you want :)
be careful not to mix this up with the function pointer declaration syntax.
There is nothing special about it, it means exactly the same as the version without parentheses. It is just an artifact of how the syntax is declared. Usually you see the use of parentheses around the function name when a function pointer is declared, e.g.
void (*function_pointer)() = nullptr;
// a function pointer to a function taking and returning void
in contrast to
void *function();
// a function declaration of a function taking void and returning void*
I think it works the same as a normal function because function pointers are declared like: void (*function)() so if you leave out the * then it should be just a function.
It corresponds to the C++ grammar. If to simplify then one of the rules for defining of the declarator looks as
declarator:
(declarator)
So you can write for example
void (function) ();
or
void ( (function) () );
or even the following way
struct A
{
void ( ( function )() const );
};
I think you may find that was:
void (*function) ();
since there is no benefit to using void (function)(); or void (((((function)))))(); for that matter, they're equivalent. If I'm mistaken and it's not a typo, the answer is that you can put as many parentheses around the function name as you like, subject to compiler limitations, as per the code for output6() below.
If I'm not mistaken, that one with the * actually declares a function pointer which can be used to hold a pointer to a function. It does not declare a function at all, just a pointer that can be used to reference a function.
Like an int pointer (for example), the function pointer can point to an arbitrary function, parameters notwhithstanding.
So for example:
#include <iostream>
void (((((output6)))))() { std::cout << 6; }
void output7() { std::cout << 7; }
void output8() { std::cout << 8; }
void (*fn)();
int main() {
fn = &output6; fn();
fn = &output7; fn();
fn = &output8; fn();
std::cout << '\n';
}
would output 678.

Calling a function reference from a string mixin

I have exported functions with quite a bit of boilerplate, and am attempting to use string mixins to help hide the mess and sugar it up. The problem is that I have no idea how I could pass an anonymous function into the string mixin. I'd like to avoid writing the function as a string if at all possible.
// The function that the anonymous function below ultimately gets passed to.
char* magic(F...)(string function(F) func) { ... }
string genDcode(string name, alias func)() {
return xformat(q{
extern(C) export char* %s(int blah) {
// What would I inject into the string in place of 'func'
// in order to call the 'func' passed into the template?
return magic(func);
}
}, name);
}
// Calls a function to generate code to mix into the global scope.
// The anonymous function must allow abritrary parameters.
mixin(genDcode!("funcName", function(string foo, float bar) {
return "Herpderp";
}));
This is of course not the full picture, and most of the boilerplate is trimmed, but it's enough to show the problem. I've thought about injecting the function pointer as an int, and casting back into a callable type, but unsurprisingly, you can only get the function pointer at runtime.
I've tried mixin templates, which elimitates the function passing problem, but the linker cannot seem to find export functions generated from such mixins. They appear to have some extra qualifiers, and I can't use a dot in the DEF file.
Old question, but a relatively new feature might help solve it: D now has a pragma(mangle) which you can put inside a mixin template to force a particular name for the linker:
mixin template genDcode(string name, alias func) {
// pragma mangle is seen by the linker instead of the name...
pragma(mangle, name) extern(C) export char* impl(int blah) {
return magic(func);
}
}
char* magic(F...)(string function(F) func) { return null; }
mixin genDcode!("funcName", function(string foo, float bar) {
return "Herpderp";
});

How to make sure a function is only called once

Suppose I have a function named caller, which will call a function named callee:
void caller()
{
callee();
}
Now caller might be called many times in the application, and you want to make sure callee is only called once. (kind of lazy initialization), you could implement it use a flag:
void caller()
{
static bool bFirst = true;
if(bFirst)
{
callee();
bFirst = false;
}
}
My opinion for this is it needs more code, and it needs one more check in every call of function caller.
A better solution to me is as follow: (suppose callee returns int)
void caller()
{
static int ret = callee();
}
But this can't handle the case if callee returns void, my solution is using the comma expression:
void caller()
{
static int ret = (callee(), 1);
}
But the problem with this is that comma expression is not popular used and people may get confused when see this line of code, thus cause problems for maintainance.
Do you have any good idea to make sure a function is only called once?
You could use this:
void caller()
{
static class Once { public: Once(){callee();}} Once_;
}
Thread-safe:
static boost::once_flag flag = BOOST_ONCE_INIT;
boost::call_once([]{callee();}, flag);
You could hide the function through a function pointer.
static void real_function()
{
//do stuff
function = noop_function;
}
static void noop_function()
{
}
int (*function)(void) = real_function;
Callers just call the function which will do the work the first time, and do nothing on any subsequent calls.
Your first variant with a boolean flag bFirst is nothing else that an explict manual implementatuion of what the compiler will do for you implictly in your other variants.
In other words, in a typical implementation in all of the variants you pesented so far there will be an additional check for a boolean flag in the generated machine code. The perfromance of all these variants will be the same (if that's your concern). The extra code in the first variant might look less elegant, but that doesn't seem to be a big deal to me. (Wrap it.)
Anyway, what you have as your first variant is basically how it is normally done (until you start dealing with such issues as multithreading etc.)
Inspired by some people, I think just use a macro to wrap comma expression would also make the intention clear:
#define CALL_ONCE(func) do {static bool dummy = (func, true);} while(0)