Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::function signature pointer vs pointer reference = no difference?

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;
  1. Why does it compile without error (with at least gcc 5.2 and clang 3.7)?

  2. How it can be fixed, so that std::function<Params> does not accept f for conversion?

like image 284
fghj Avatar asked Mar 14 '23 11:03

fghj


1 Answers

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.

like image 69
Sebastian Redl Avatar answered Mar 17 '23 01:03

Sebastian Redl