C++ struct directly followed by parentheses to form a functor? - c++

When I read std::function, I find the following syntax confusing. What does a struct followed directly by empty parentheses do here? It works equivalent to declare a struct object instead and call its operator.
#include <iostream>
using namespace std;
int main() {
struct F {
bool operator()(int a) {
return a>0;
}
};
function<bool(int)> f = F(); //What does the syntax F() mean here?
struct F ff;
cout << f(1) <<endl;
cout << ff(1) <<endl;
return 0;
}

What does the syntax F() mean here?
It means construct an object of type F using the default constructor.
A std::function can be constructed using any callable object that meets its calling criteria. In your particular use case, an instance of F meets those criteria for std::function<bool(int)>. Hence,
function<bool(int)> f = F();
is a valid statement to construct f.

Dont get confused by the fact that calling the default constuctor also uses (). This
function<bool(int)> f = F();
calls the constructor and assigns the object to the function f, while this
f(1)
calls the operator().

Related

Initialize a lambda function in the body of a class constructor

I can compile the following code without any problem (using gcc 11.1.0):
#include <iostream>
template <typename Func>
class K {
Func f;
public:
K(Func _f): f{_f} {};
void do_thing(int x) {f(x);};
};
int main()
{
auto f = [](int x) {std::cout << x << std::endl;};
K kl{f};
kl.do_thing(5);
return 0;
}
however I would like to perform some check in the constructor of the class K (for instance some std::is_convertible_v inside some bool function), so I tried to modify the code to
#include <iostream>
template <typename Func>
class K {
Func f;
public:
K(Func _f) {
...
f = _f;};
void do_thing(int x) {f(x);};
};
int main()
{
auto f = [](int x) {std::cout << x << std::endl;};
K kl{f};
kl.do_thing(5);
return 0;
}
which however gives me some error message
error: use of deleted function ‘main()::<lambda(int)>::<lambda>()’
and then
note: a lambda closure type has a deleted default constructor
This confuses me a lot since I cannot understand how it is possible that the former piece of code could compile since the lambda function has not default constructor.
Question
How can I set my f inside the body of the constructor? (This is just a MWE and in my case the class is a bit more complex and the checks I mentioned before make sense.)
How can I initialize my f inside the body of the constructor?
You can't. f = _f; inside the constructor body is assignment but not initialization. So f will be default-initialized firstly, then enter the constructor body (to perform assignment).
You might use std::function instead; which could be default-initialized, then you can assign it in constructor body.
BTW: Since C++20 your code will compile fine even it might not work as you expected (depending on the ... part). For lambdas,
If no captures are specified, the closure type has a defaulted default constructor. Otherwise, it has no default constructor (this includes the case when there is a capture-default, even if it does not actually capture anything).
Is this what you are looking for?
It is the generic solution, not making any assumptions on the signature of Fn
#include <iostream>
#include <utility>
template <typename Fn>
class K
{
public:
explicit K(const Fn& fn) :
m_fn{ fn }
{
};
template<typename... args_t>
auto do_thing(args_t&&... args)
{
return m_fn(std::forward<args_t>(args)...);
}
private:
Fn m_fn;
};
int main()
{
auto f = [](int x) {std::cout << x << std::endl; };
K kl{ f };
kl.do_thing(5);
}

Unexpected behavior after assignment of function object to function wrapper

I was searching a bug in an application, which I've finally fixed but didn't understand completely.
The behavior can be reproduced with the following simple program:
#include <iostream>
#include <memory>
#include <functional>
struct Foo
{
virtual int operator()(void) { return 1; }
};
struct Bar : public Foo
{
virtual int operator()(void) override { return 2; }
};
int main()
{
std::shared_ptr<Foo> p = std::make_shared<Bar>();
std::cout << (*p)() << std::endl;
std::function<int(void)> f;
f = *p;
std::cout << f() << std::endl;
return 0;
}
The output of the line
std::cout << (*p)() << std::endl;
is 2, which is as I expected, of course.
But the output of the line
std::cout << f() << std::endl;
is 1. This was surprising me. I even was surprised that the assignment f = *p is allowed and doesn't cause an error.
I don't ask for a workaround, because I fixed it by a lambda.
My question is, what is happening when I do f = *p and why is the output 1 rather than 2?
I've reproduced the issue with gcc (MinGW) and Visual Studio 2019.
Further I want to mention that the output of
Bar b;
std::function<int(void)> f1 = b;
std::cout << f1() << std::endl;
is 2, again.
Object slicing happens here.
The point is given f = *p;, p is of type std::shared_ptr<Foo>, then the type of *p is Foo& (instead of Bar&). Even the assignment operator of std::function takes argument by reference, but
4) Sets the target of *this to the callable f, as if by executing function(std::forward<F>(f)).swap(*this);.
Note that the F above is deduced as Foo& too. And the constructor of std::function takes argument by value, object slicing happens, the effect becomes that f is assigned from an object of type Foo which is slice-copied from *p.
template< class F >
function( F f );
This is regular slicing, hidden under a layer of std::function and std::shared_ptr.
f = *p;
is valid because *p is a callable object with an appropriate operator(), and that is one of the things you can wrap in a std::function.
The reason that it doesn't work is that it copies *p – and that is a Foo&, not a Bar&.
This adaptation of your last example would behave the same:
Bar b;
Foo& c = b;
std::function<int(void)> f1 = c;
std::cout << f1() << std::endl;
Slicing
This is a case of slicing.
The reason is assignment operator of std::function (as demonstrated in another answer as well) which states:
Sets the target of *this to the callable f, as if by executing
function(std::forward(f)).swap(*this);. This operator does not
participate in overload resolution unless f is Callable for argument
types Args... and return type R. (since C++14)
https://en.cppreference.com/w/cpp/utility/functional/function/operator%3D
If you simplify and strip down the example - you can easily see what's going on:
Foo* p = new Bar;
Foo f;
f = *p;//<-- slicing here since you deref and then copy the object
It looks like you were aiming at obtaining a pointer to the overridden virtual function - unfortunately, theres no easy way to unroll the virtual function lookup as that is implemented via a runtime lookup table. However an easy workaround might be to use a lambda to wrap (As the OP also mentions):
f = [p]{return (*p)();};
A more suitable solution could also be to just a use reference_wrapper:
f = std::ref(p);
The static type of the pointer p is Foo.
So in this statement
f = *p;
there left operand *p has the type Foo that is there is slicing.

compile error about template deduction on c++

#include <iostream>
template <int N>
class X {
public:
using I = int;
void f(I i) {
std::cout << "i: " << i << std::endl;
}
};
template <int N>
void fppm(void (X<N>::*p)(typename X<N>::I)) {
p(0);
}
int main() {
fppm(&X<33>::f);
return 0;
}
I just don't understand the compile error message of the code.
error: called object type 'void (X<33>::*)(typename X<33>::I)' is not a function or function pointer
p(0);
I think p is a function which returns void and takes int as its argument. But apparently, it's not. Could somebody give me clue?
Since p is a pointer to a nonstatic member function, you need an instance to call it with. Thus, first instantiate an object of X<33> in main:
int main() {
X<33> x;
fppm(x, &X<33>::f); // <-- Signature changed below to accept an instance
Then in your function, change the code to accept an instance of X<N> and call the member function for it:
template <int N>
void fppm(X<N> instance, void (X<N>::*p)(typename X<N>::I)) {
(instance.*p)(0);
}
The syntax may look ugly but the low precedence of the pointer to member operator requires the need for the parentheses.
As denoted in the comments already, p is a pointer to member function, but you call it like a static function (p(0);). You need a concrete object to call p on:
X<N> x;
(x.*p)(0);
// or:
X<N>* xx = new X<N>();
(xx->*p)(0);
delete xx;
Be aware that the .*/->* operators have lower precedence than the function call operator, thus you need the parentheses.
Side note: Above is for better illustration, modern C++ might use auto keyword and smart pointers instead, which could look like this:
auto x = std::make_unique<X<N>>();
(x.get()->*p)(0);

What's the function signature of a member function?

I'm having trouble understanding function signatures and pointers.
struct myStruct
{
static void staticFunc(){};
void nonstaticFunc(){};
};
int main()
{
void (*p)(); // Pointer to function with signature void();
p = &myStruct::staticFunc; // Works fine
p = &myStruct::nonstaticFunc; // Type mismatch
}
My compiler says that the type of myStruct::nonstaticFunc() is void (myStruct::*)(), but isn't that the type of a pointer pointing to it?
I'm asking because when you create an std::function object you pass the function signature of the function you want it to point to, like:
std::function<void()> funcPtr; // Pointer to function with signature void()
not
std::function<void(*)()> funcPtr;
If I had to guess based on the pattern of void() I would say:
void myStruct::();
or
void (myStruct::)();
But this isn't right. I don't see why I should add an asterisk just because it's nonstatic as opposed to static. In other words, pointer void(* )() points to function with signature void(), and pointer void(myStruct::*)() points to function with signature what?
To me there seems to be a basic misunderstanding of what a member pointer is. For example if you have:
struct P2d {
double x, y;
};
the member pointer double P2d::*mp = &P2d::x; cannot point to the x coordinate of a specific P2d instance, it is instead a "pointer" to the name x: to get the double you will need to provide the P2d instance you're looking for... for example:
P2d p{10, 20};
printf("%.18g\n", p.*mp); // prints 10
The same applies to member functions... for example:
struct P2d {
double x, y;
double len() const {
return sqrt(x*x + y*y);
}
};
double (P2d::*f)() const = &P2d::len;
where f is not a pointer to a member function of a specific instance and it needs a this to be called with
printf("%.18g\n", (p.*f)());
f in other words is simply a "selector" of which of the const member functions of class P2d accepting no parameters and returning a double you are interested in. In this specific case (since there is only one member function compatible) such a selector could be stored using zero bits (the only possible value you can set that pointer to is &P2d::len).
Please don't feel ashamed for not understanding member pointers at first. They're indeed sort of "strange" and not many C++ programmers understand them.
To be honest they're also not really that useful: what is needed most often is instead a pointer to a method of a specific instance.
C++11 provides that with std::function wrapper and lambdas:
std::function<double()> g = [&](){ return p.len(); };
printf("%.18g\n", g()); // calls .len() on instance p
std::function<void()> funcPtr = std::bind(&myStruct::nonstaticFunc, obj);
Is how you store a member function in std::function. The member function must be called on a valid object.
If you want to delay the passing of an object until later, you can accomplish it like this:
#include <functional>
#include <iostream>
struct A {
void foo() { std::cout << "A::foo\n"; }
};
int main() {
using namespace std::placeholders;
std::function<void(A&)> f = std::bind(&A::foo, _1);
A a;
f(a);
return 0;
}
std::bind will take care of the details for you. std::function still must have the signature of a regular function as it's type parameter. But it can mask a member, if the object is made to appear as a parameter to the function.
Addenum:
For assigning into std::function, you don't even need std::bind for late binding of the object, so long as the prototype is correct:
std::function<void(A&)> f = &A::foo;
p = &myStruct::staticFunc; // Works fine
p = &myStruct::nonstaticFunc; // Type mismatch
Reason : A function-to-pointer conversion never applies to non-static member functions because an lvalue that refers to a non-static member function
cannot be obtained.
pointer void(* )() points to function with signature void(), and pointer void(myStruct::*)() points to function with signature what?
myStruct:: is to make sure that the non-static member function of struct myStruct is called (not of other structs, as shown below) :
struct myStruct
{
static void staticFunc(){};
void nonstaticFunc(){};
};
struct myStruct2
{
static void staticFunc(){};
void nonstaticFunc(){};
};
int main()
{
void (*p)(); // Pointer to function with signature void();
void (myStruct::*f)();
p = &myStruct::staticFunc; // Works fine
p = &myStruct2::staticFunc; // Works fine
f = &myStruct::nonstaticFunc; // Works fine
//f = &myStruct2::nonstaticFunc; // Error. Cannot convert 'void (myStruct2::*)()' to 'void (myStruct::*)()' in assignment
return 0;
}
When you use a pointer, std::function or std::bind to refer to a non-static member function (namely, "method" of class Foo), the first param must be a concrete object of class Foo, because non-static method must be called by a concrete object, not by Class.
More details: std::function and
std::bind.
The answer is in the doc.
Pointer to member declarator: the declaration S C::* D; declares D as
a pointer to non-static member of C of type determined by
decl-specifier-seq S.
struct C
{
void f(int n) { std::cout << n << '\n'; }
};
int main()
{
void (C::* p)(int) = &C::f; // pointer to member function f of class C
C c;
(c.*p)(1); // prints 1
C* cp = &c;
(cp->*p)(2); // prints 2
}
There are no function with signature void (). There are void (*)() for a function or void (foo::*)() for a method of foo. The asterisk is mandatory because it's a pointer to x. std::function has nothing to do with that.
Note: Your confusion is that void() is that same signature that void (*)(). Or even int() <=> int (*)(). Maybe you think that you can write int (foo::*) to have a method pointer. But this is a data member pointer because the parenthesis are optional, int (foo::*) <=> int foo::*.
To avoid such obscure syntax you need to write your pointer to function/member with the return type, the asterisk and his parameters.

Is there a use case for std::function that is not covered by function pointers, or is it just syntactic sugar? [duplicate]

This question already has answers here:
Why do we use std::function in C++ rather than the original C function pointer? [duplicate]
(3 answers)
Closed 9 years ago.
The notation for std::function is quite nice when compared to function pointers. However, other than that, I can't find a use case where it couldn't be replaced by pointers. So is it just syntactic sugar for function pointers?
std::function<> gives you the possibility of encapsulating any type of callable object, which is something function pointers cannot do (although it is true that non-capturing lambdas can be converted to function pointers).
To give you an idea of the kind of flexibility it allows you to achieve:
#include <functional>
#include <iostream>
#include <vector>
// A functor... (could even have state!)
struct X
{
void operator () () { std::cout << "Functor!" << std::endl; }
};
// A regular function...
void bar()
{
std::cout << "Function" << std::endl;
}
// A regular function with one argument that will be bound...
void foo(int x)
{
std::cout << "Bound Function " << x << "!" << std::endl;
}
int main()
{
// Heterogenous collection of callable objects
std::vector<std::function<void()>> functions;
// Fill in the container...
functions.push_back(X());
functions.push_back(bar);
functions.push_back(std::bind(foo, 42));
// And a add a lambda defined in-place as well...
functions.push_back([] () { std::cout << "Lambda!" << std::endl; });
// Now call them all!
for (auto& f : functions)
{
f(); // Same interface for all kinds of callable object...
}
}
As usual, see a live example here. Among other things, this allows you to realize the Command Pattern.
std::function is designed to represent any kind of callable object. There are plenty of callable objects that cannot be represented in any way by a function pointer.
A functor:
struct foo {
bool operator()(int x) { return x > 5; }
};
bool (*f1)(int) = foo(); // Error
std::function<bool(int)> f2 = foo(); // Okay
You cannot create an instance of foo and store it in a bool(*)(int) function pointer.
A lambda with a lambda-capture:
bool (*f1)(int) = [&](int x) { return x > y; }; // Error
std::function<bool(int)> f2 = [&](int x) { return x > y; }; // Okay
However, a lambda without a capture can be converted to a function pointer:
The closure type for a lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type’s function call operator. The value returned by this conversion function shall be the address of a function that, when invoked, has the same effect as invoking the closure type’s function call operator.
Implementation-defined callable return values:
bool foo(int x, int y) { return x > y; };
bool (*f1)(int) = std::bind(&foo, std::placeholders::_1, 5); // Error (probably)
std::function<bool(int)> f2 = std::bind(&foo, std::placeholders::_1, 5); // Okay
std::bind's return value is an implementation-defined callable object. Only how that object may be used is specified by the standard, not its type.