For educational reasons, I'm studying the C language using clang-12 std=c 17
And I have the following code:
Fullcode
#include <cstdio>
#include <iostream>
#include <type_traits>
using namespace std;
struct S {
void operator()(int) {}
};
int main()
{
S(*d)(int);
//d = whatValue??
return 0;
}
I'm studying the types of variables that exist in the C language, and I came across this situation above.
What value can I assign to the d
variable?
Could it be a language bug? I've already researched several topics on stackoverflow and cppreference and haven't found any way to initialize this variable S(*d)(int)
.
CodePudding user response:
The variable d
is a pointer to a function taking an int
as argument and returning an S
. Note that it cannot point to non-static
member functions. You could, e.g., use it like this:
struct S {
void operator()(int) {}
};
S f(int) { return S(); }
int main()
{
S(*d)(int) = &f;
S rc = d(17);
}
As functions decay to pointer types, you can actually leave the &
out. The same isn't true for non-static
member functions, though. If you wanted to get a pointer to a member function of S
taking an int
as argument and returning void
(your operator()
returns void
not S
) you'd need to use the &
:
int main() {
void (S::*d)(int) = &S::operator();
S obj;
S rc = (obj.*d)(17); // use d
}
Pointer to member functions are different to pointer to functions because they have an implicit first argument: the this
pointer. With C it is quite rare that pointer to functions are used for other reasons than interfacing C code: using std::function<void(int)>
is more flexible, although also type-erase and most likely involving a virtual
function call and not being inlinable. If the function can be a function template it is common to pass function objects which are std::invoke()
ed (instead of directly called) which support function pointers, pointer to member functions, pointer to non-function members, lambdas, functions, etc.
CodePudding user response:
What value can I assign to the d variable?
d
is a pointer to function, and as such you can assign a function that returns S
and accepts int
as a parameter. Example:
S some_function(int);
d = some_function;
Could it be a language bug?
No.