1

In this question, the OP claims that the third line in the main function is casting the return value of std::bind to std::function.

However, it looks like a simple constructor call to me.

Is there a legitimate way to actually cast the return value of std::bind to std::function without constructing a new object?

Alternately, is it kosher (not undefined behavior) to cast the the address of a return value of std::bind to std::function* and then invoke it by deferencing it?

Assume I know the appropriate template parameters for std::function. That is, assume they are the same template parameters which would have been used if we were constructing an instance of std::function from the return value of std::bind.

Community
  • 1
  • 1
merlin2011
  • 71,677
  • 44
  • 195
  • 329

2 Answers2

2

The standard calls this an explicit type conversion with functional notation. Essentially it is used to construct a value of the specified type. Although it may look like a constructor call, there's actually no way to directly call a constructor in C++.

Is there a legitimate way to actually cast the return value of std::bind to std::function without constructing a new object?

No. The return type of std::bind is unspecified; it can return anything so long as it provides the correct operations and semantics. There's no way you could just consider it as a std::function in a portable manner.

Alternately, is it kosher (not undefined behavior) to cast the the address of a return value of std::bind to std::function* and then invoke it by deferencing it?

No, that's undefined behaviour.

TartanLlama
  • 63,752
  • 13
  • 157
  • 193
0

Type of std::bind expression is different from std::function type. In some cases, it cannot even be converted to std::function. So, no, you cannot cast bind object to std::function without constructing. Compiler can allow implicit conversion, though.

Same applies to lambda expression.

Andrei R.
  • 2,374
  • 1
  • 13
  • 27
  • 3
    In what case can it not be converted? I am currently under the understanding that it can always be converted but if I misread the standard I would like to know. – merlin2011 May 16 '16 at 08:12
  • 1
    if you bind with value of noncopyable type (`std::unique_ptr`, for instance) by `std::move`. Thus, bind object becomes noncopyable, but `std::function` is. – Andrei R. May 16 '16 at 08:41