Is it possible to create/generate a pointer declaration similar to:
void (*foo)(int, float);
bool (*foo)();
char (*foo)(char, int);
But without knowing the type of the arguments or the return type until run-time.
The function declaration would be read from a string which would specify the return and argument type (if any) then (if possible) stored in a c++ container.
Can it be done at run-time (not compile-time) ? And also C++11 can be used if necessary.
I really doubt this can be done in a statically typed language like C++ but if it can be done then what approach would someone use. No need for code (but it's appreciated) just some guidance to what must be used.
EDIT:
After testing several ideas it turns out that it can't be achieved (directly) with C++. Luckily I found the dyncall library which allows me do do it (indirectly) and on a quite large number of platforms.
Example function:
double sqrt(double x);
Using dyncall to call the function:
double r;
DCCallVM* vm = dcNewCallVM(4096);
dcMode(vm, DC_CALL_C_DEFAULT);
dcReset(vm);
dcArgDouble(vm, 4.2373);
r = dcCallDouble(vm, (DCpointer)&sqrt);
dcFree(vm);
Strings can also be used to declare the structure of a function.
C function prototype dyncall signature
void f1(); ")v"
int f2(int, int); "ii)i"
long long f3(void*); "p)L"
void f3(int**); "p)v"
double f4(int, bool, char, double, const char*); "iBcdZ)d"
It depends how many types of arguments you will handle. Technically - you can do everything in C++, just sometimes it's not as simple as you would want it to be.
You could use the delegate pattern:
class baseDelegate(){};
template<typename retT, typename paramT>
class delegate: public baseDelegate{
public:
retT (*ptr)(paramtT);
};
vector<baseDelegate*> yourDelegateList;
Since you tagged the topic as C++11, you could also use std::function, variadic templates and so on, to make it easier. The above code is just an example.
You could doe something like
void function (string &arg, …) ;
and use the variable arguments feature of C++.
You need at lest one fixed argument though.
Generally, what you are describing is not a good thing in C++ as you indicate.
Related
void f() means that f returns nothing. If void returns nothing, then why we use it? What is the main purpose of void?
When C was invented the convention was that, if you didn't specify the return type, the compiler automatically inferred that you wanted to return an int (and the same holds for parameters).
But often you write functions that do stuff and don't need to return anything (think e.g. about a function that just prints something on the screen); for this reason, it was decided that, to specify that you don't want to return anything at all, you have to use the void keyword as "return type".
Keep in mind that void serves also other purposes; in particular:
if you specify it as the list of parameters to a functions, it means that the function takes no parameters; this was needed in C, because a function declaration without parameters meant to the compiler that the parameter list was simply left unspecified. In C++ this is no longer needed, since an empty parameters list means that no parameter is allowed for the function;
void also has an important role in pointers; void * (and its variations) means "pointer to something left unspecified". This is useful if you have to write functions that must store/pass pointers around without actually using them (only at the end, to actually use the pointer, a cast to the appropriate type is needed).
also, a cast to (void) is often used to mark a value as deliberately unused, suppressing compiler warnings.
int somefunction(int a, int b, int c)
{
(void)c; // c is reserved for future usage, kill the "unused parameter" warning
return a+b;
}
This question has to do with the history of the language: C++ borrowed from C, and C used to implicitly type everything untyped as int (as it turned out, it was a horrible idea). This included functions that were intended as procedures (recall that the difference between functions and procedures is that function invocations are expressions, while procedure invocations are statements). If I recall it correctly from reading the early C books, programmers used to patch this shortcoming with a #define:
#define void int
This convention has later been adopted in the C standard, and the void keyword has been introduced to denote functions that are intended as procedures. This was very helpful, because the compiler could now check if your code is using a return value from a function that wasn't intended to return anything, and to warn you about functions that should return but let the control run off the end instead.
In imperative programming languages such as C, C++, Java, etc., functions and methods of type void are used for their side effects. They do not produce a meaningful value to return, but they influence the program state in one of many possible ways. E.g., the exit function in C returns no value, but it has the side effect of aborting the application. Another example, a C++ class may have a void method that changes the value of its instance variables.
void() means return nothing.
void doesn't mean nothing. void is a type to represent nothing. That is a subtle difference : the representation is still required, even though it represents nothing.
This type is used as function's return type which returns nothing. This is also used to represent generic data, when it is used as void*. So it sounds amusing that while void represents nothing, void* represents everything!
Because sometimes you dont need a return value. That's why we use it.
If you didn't have void, how would you tell the compiler that a function doesn't return a value?
Cause consider some situations where you may have to do some calculation on global variables and put results in global variable or you want to print something depending on arguments , etc.. In these situations you can use the method which dont return value.. i.e.. void
Here's an example function:
struct SVeryBigStruct
{
// a lot of data here
};
SVeryBigStruct foo()
{
SVeryBigStruct bar;
// calculate something here
return bar;
}
And now here's another function:
void foo2(SVeryBigStruct& bar) // or SVeryBigStruct* pBar
{
bar.member1 = ...
bar.member2 = ...
}
The second function is faster, it doesn't have to copy whole struct.
probably to tell the compiler " you dont need to push and pop all cpu-registers!"
Sometimes it can be used to print something, rather than to return it. See http://en.wikipedia.org/wiki/Mutator_method#C_example for examples
Functions are not required to return a value. To tell the compiler that a function does not return a value, a return type of void is used.
I've come across some C++ code that looks like this (simplified for this post):
(Here's the function prototype located in someCode.hpp)
void someFunction(const double & a, double & b, const double c = 0, const double * d = 0);
(Here's the first line of the function body located in someCode.cpp that #include's someCode.hpp)
void someFunction(const double & a, double & b, const double c, const double * d);
Can I legally call someFunction using:
someFunction(*ptr1, *ptr2);
and/or
someFunction(*ptr1, *ptr2, val1, &val2);
where the variables ptr1, ptr2, val, and val2 have been defined appropriately and val1 and val2 do not equal zero? Why or why not?
And if it is legal, is this syntax preferred vs overloading a function to account for the optional parameters?
Yes, this is legal, this is called default arguments. I would say it's preferred to overloading due to involving less code, yes.
Regarding your comment about const, that doesn't apply to the default value itself, it applies to the argument. If you have an argument of type const char* fruit = "apple", that doesn't mean it has to be called with a character pointer whose value is the same as the address of the "apple" string literal (which is good, since that would be hard to guarantee). It just means that it has to be called with a pointer to constant characters, and tells you that the function being called doesn't need to write to that memory, it is only read from.
Yes, the parameters are optional and when you don't pass them, the given default values will be used.
It has some advantages and disadvantages to use default parameter values instead of overloading. The advantage is less typing in both interface and implementation part. But the disadvantage is that the default value is a part of interface with all its consequences. Then when you change the default value, you for example need to recompile a lot of code instead of a single file when using overloading.
I personally prefer default parameters.
I'd like to expand a bit on whether Default Parameters are preferred over overloading.
Usually they are for all the reasons given in the other answers, most notably less boilerplate code.
There are also valid reasons that make overloading a better alternative in some situations:
Default values are part of the interface, changes might break clients (as #Juraj already noted)
Additionally Overloads make it easier to add additional (combinations of) parameters, without breaking the (binary) interface.
Overloads are resolved at compile time, which can give the compiler better optimization (esp inlining) possibilities. e.g. if you have something like this:
void foo(Something* param = 0) {
if (param == 0) {
simpleAlgorithm();
} else {
complexAlgorithm(param);
}
}
It might be better to use overloads.
Can I legally call someFunction using:
someFunction(*ptr1, *ptr2);
Absolutely! Yes, the other 2 variables that the function accepts would have default values you have set in the header file which is zero for both the arguments.
But if you do supply the 3rd and the 4th argument to the function, then those values are considered instead of the default values.
I know that generally, a function pointer is declared like this:
void __stdcall my_func(int i) {} // for assigning
void (__stdcall * my_ptr)(int) = &my_func;
Now I had several functions which take a function pointer as their argument:
void calling_func(void (__stdcall * callback)(int)) { *callback(1); }
In the header file, I just removed the name of the thing:
void calling_func(void (__stdcall *)(int));
and voilá, that worked ... and got me thinking: If that is a complete type declaration, couldn't one use the normal TYPE NAME = VALUE syntax also for function pointers?
I tried to declare:
( void (__stdcall *)(int) ) callback = &my_func;
and it also compiles! Why isn't this used more often? Are there flaws with this notation? To me it seems that it would greatly ease the use of function pointers ... also in typedefs, for example: generally it's typedef OLDNAME NEWNAME, just with function pointers it's this weird inside-out syntax where the new name is actually in the middle of the whole expression. Let alone the notation for functions returning a function pointer ...
That is not a declaration, it's a cast of callback, which is then assigned to.
Are you sure you didn't have a pre-existing declaration in scope?
Doesn't compile for me. AFAIK it's not valid C++.
You can fake it, though!
template <typename T>
struct identity {
typedef T type;
};
identity<void(*)(int)>::type callback = &my_func;
Or use something like boost::function (or std::function) for the ultimate wins.
I much prefer typedefing my function pointers, and have yet to have problems with it.
Typedef, if I understand it correctly, doesn't so much make a new type as an alias to the other one (which is why size_t and unsigned int can be used interchangeably without compiler complaints, for example). So, for function pointer types you use often, typedefs make them a lot easier to work with.
For function pointer typedefs, the syntax goes:
typedef IObject * (*CreateFunc )(int, Core *);
With the desired type name on the inside (not much different from what you're doing now). You can specify most function modifiers (__stdcall, __declspec, etc), they come just inside the parentheses before the * name.
You can call, assign and get the value of these quite easily, as well as converting them to void * for passing (when the type is unknown).
I have various functions with two int arguments (I write both the functions and the calling code myself). I am afraid to confuse the order of argument in some calls.
How can I use type safety to have compiler warn me or error me if I call a function with wrong sequence of arguments (all arguments are int) ?
I tried typedefs: Typedef do not trigger any compiler warnings or errors:
typedef int X; typedef int Y;
void foo(X,Y);
X x; Y y;
foo(y,x); // compiled without warning)
You will have to create wrapper classes. Lets say you have two different units (say, seconds and minutes), both of which are represented as ints. You would need something like the following to be completely typesafe:
class Minute
{
public:
explicit Minute(int m) : myMinute(m) {}
operator int () const { return myMinute; }
private:
int myMinute;
};
and a similar class for seconds. The explicit constructor prevents you accidentally using an int as a Minute, but the conversion operator allows you to use a Minute anywhere you need an int.
typedef creates type aliases. As you've discovered, there's no type safety there.
One possibility, depending on what you're trying to achieve, is to use enum. That's not fully typesafe either, but it's closer. For example, you can't pass an int to an enum parameter without casting it.
Get a post-it note. Write on it, in big letters, "X FIRST! THEN Y!" Stick it to your computer screen. I honestly don't know what else to advise. Using wrapper classes is surely overkill, when the problem can be solved with a post-it and a magic marker.
Reading a question in stackoverflow, I wondered whether it's possible to declare a function that takes a pointer to itself. I.e. to make such declaration of foo, for which the following would be correct:
foo(foo);
The simpliest idea is casting to another function pointer (can't cast to void*, since it may be smaller), so the function declaration looks like this:
void foo(void (*)());
While that's OK in C (and will work with casting in C++), I wonder, whether it can be done without such hard "reinterpret" casting or losing type information.
In other words, I want the following declaration:
void foo( void (*)( void (*)( void (*) ( ... ))));
but, of course, unlimited declarations are impossible. Naive typedefing doesn't help either.
C++ templates are welcome, even if they make the calling code (foo(foo)) look a bit less succinct, but still finite.
C-style answers that show, how one can drop type information without casting, or other tricks of that sort are, of course, interesting, but won't be accepted.
Apparently not - see this thread. The type required here would always be infinite.
Another dirty trick.
void Foo( ... )
{
}
int main()
{
Foo( Foo );
}
Above program will compile without any error. But it is not recursive. Following modified function is recursive version with a limiter.
#define RECURSIVE_DEPTH (5)
typedef void ( *FooType )( int, ... );
void Foo( int Depth, ... )
{
void ( *This )( int, ... );
va_list Arguments;
va_start( Arguments, Depth );
if( Depth )
{
This = va_arg( Arguments, FooType );
This( Depth - 1, This );
}
va_end ( Arguments );
}
int main()
{
Foo( RECURSIVE_DEPTH, Foo );
}
YES
It's a variant of "Can you write a function that returns a pointer to itself?", except that in your case, the function type recursively appears as an argumkent, not as the return type. Herb Sutters answer is reusable, though: wrap the pointer in a forward-declared proxy class.
Generally I agree with Dario - making this on type level seems impossible.
But you can use classes ("strategy pattern"):
class A {
void evil(A a) { // a pointer to A is ok too
}
};
You can even add operator():
void operator()(A a) { return evil(a); }
Generally such things are better done in FP languages. Haskell version is simply:
data Evil = Evil (Evil -> Integer)
This uses a wrapper (Evil) that corresponds to using a class.
From the questioner: what this answer lacked was the ability to pass several different functions as an argument of one of them. This can be solved either by making evil() virtual or by explicitly storing in the object a function pointer that implements it (which is basically the same).
With this clarification, the answer is good enough to be accepted.
A related problem is returning a function pointer of same type. It comes up when implementing state machines, so it got its own entry in the C FAQ.
The same workarounds can be applied to your problem.
I don't believe you can have a function that can take itself as an argument in C++ without some kind of trickery, such as putting your function in a class, and having the function take that class as an argument.
Another way that will be possible once the new C++ standard hits is to use lambdas, and have the lambda capture itself. I think it would go something like this:
auto recursive_lambda = [&recursive_lambda] { recursive_lambda(); };
Be warned that such a statement is totally untested in any compiler that supports lambdas. Your mileage may vary.
This is a perfectly valid use of void *.
typedef void T(void *);
void f(T *probably_me)
{
(*probably_me)(f);
}
If a function could take itself as an argument, then it could perform anonymous recursion by calling itself. But recursion is impossible in simply-typed lambda calculus (which is basically what you have here, with function types). You need to implement a fixed-point combinator using recursive functions or recursive types in order to perform anonymous recursion.