So I have a callback defined as:
struct S {
int a{3};
};
using callback = std::function<void(S const&)>;
And want to call it with some function:
void f(callback&& cb) { cb(S{}); }
I noticed that the compiler did not care whether I specified the callback with S
(value) or S const&
(const reference) even though only the latter explicitly matches the signature:
int main()
{
f([](S const& s) { std::cout << s.a << std::endl; });
f([](S s) {
s.a = 5;
std::cout << s.a << std::endl;
});
return 0;
}
So my question is: Is this valid C++ or is it just some compiler extension (I use GCC 11)?
It would be nice to be able to have both so I can get a copy when I need to, but avoid it when not needed.
As an aside: How is it possible from the callside (here f
) to know whether to pass by reference or copy? Or is this delegated to within the std::function
s call operator?
For code example:
https://godbolt.org/z/afn6anWdv