Austin
Austin

Reputation: 7319

Simple way to call a command-line argument as a function in C++?

Is there any way a C++ beginner can implement something like this? For example:

./timerprogram sortalgorithm.cpp

where timerprogram.cpp at some point does something like argv[1](); to run the function whose name is given by the command-line argument?

Assuming that sortalgorithm.cpp was self-contained and had an array to sort already. I don't need the timing part, just how to call as a function a command-line argument. Is there anything build-in to C++ that will allow me to do this?

Upvotes: 3

Views: 272

Answers (2)

fluffybunny
fluffybunny

Reputation: 506

No. The answer is no.

Most of the stuff you see about this are inside jokes.

There are silly ways to make it look like its working, but they are silly, and certainly not for beginners.

Upvotes: 2

Sam Varshavchik
Sam Varshavchik

Reputation: 118292

Function names are used mostly by the compiler, to compile the code, and figure out when something calls a function "where" it actually is. Also by the linker too, but that's beside the point.

Although some C++ implementations might provide run-time extensions or libraries that can be used to resolve an address given its symbol name, the easiest and the most portable solution is for your program to simply have an array of strings, with your function names, and a pointer to the corresponding function.

Then, your main() searches the array for the requested function name, and invokes it via its function pointer.

How to implement this simple solution is going to be your homework assignment.

Upvotes: 2

Related Questions