Here is code example:
#include <string>
#include <functional>
struct Foo {};
typedef bool func_type(Foo *&, const std::string&);
typedef std::function<bool(Foo*&, const std::string&)> FunctionalType;
bool f(Foo *, const std::string&)
{
}
int main()
{
#if 1
func_type *func;
func = f;
#else
FunctionalType f2;
f2 = f;
#endif
}
As you see, I have declared function type with "reference to pointer" as the first argument Foo *&
, and I expect that function with just "pointer" as the first argument Foo *
cannot be assigned to a variable of this type.
The #if 1
region fails to compile (as I expect); however, the alternative did not emit any errors:
FunctionalType f2;
f2 = f;
Why does it compile without error (with at least gcc 5.2 and clang 3.7)?
How it can be fixed, so that std::function<Params>
does not accept f
for conversion?
std::function<R(Ts...)>
is defined as a type whose objects can represent any function that can be called with arguments Ts...
and whose return value is convertible to R
.
Since your function f
can be called with an lvalue of type T*
as the first argument (which is the requirement that your Foo *&
imposes), it is a valid function to be stored in your std::function
.
There is no way to suppress this behavior that I know of.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With