Std :: function sign pointer vs reference pointer = no difference?

Here is a sample code:

 #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 can see, I declared a function type with a "pointer reference" as the first argument Foo *&, and I expect that a function with just a "pointer" as the first argument Foo *cannot be assigned to this type variable.

The scope #if 1cannot compile (as I expect); however, the alternative did not emit any errors:

FunctionalType f2;
f2 = f;
  • Why does it compile without errors (with at least gcc 5.2 and clang 3.7)?

  • How can this be fixed so that it std::function<Params>does not accept ffor conversion?

+4
source share
2 answers

std::function .

++, , "" .

bool(Foo*&, const std::string&).

, Args... R(Args...) std::function Foo*&, const std::string&, , Foo* const std::string&.

std::function , .

, :

template<class T>
struct reference_only {
  T& t;
  operator T&(){ return t; }
  operator T()=delete;
  reference_only(T& tin):t(tin){}
};

:

typedef std::function<void(reference_only<Foo*>)> FunctionalType;

, ( Foo*& ).

, , .

+3

std::function<R(Ts...)> , , Ts... R.

f lvalue T* ( , Foo *&), , std::function.

, .

+4

Source: https://habr.com/ru/post/1611607/


All Articles