1

Please consider the following code snippet:

#include <iostream>
#include <functional>

typedef std::function<double()> doubleFunc;

double add(doubleFunc a, doubleFunc b)
{
  return a() + b();
}

double constValue(double value)
{
  return value;
}

int main(int argc, char *argv[])
{
  doubleFunc c1 = std::bind(constValue, 10);
  doubleFunc c2 = std::bind(constValue, 20);
  doubleFunc c3 = std::bind(constValue, 30);

  // this compiles fine:
  std::cout << add(c1, std::bind(add, c2, c3)) << std::endl;

  // here a cast is required:
  doubleFunc result = std::bind(add, c1, static_cast<doubleFunc>(std::bind(add, c2, c3)));
  std::cout << result() << std::endl;

  // similar line (but without cast to doubleFunc) won't compile:
  // doubleFunc result2 = std::bind(add, c1, std::bind(add, c2, c3));
}

Why is cast to doubleFunc required for third argument in call to std::bind in last (commented out) line?

This is GCC 4.8 compilation error:

error: conversion from ‘std::_Bind_helper<false, double (&)(std::function<double()>, std::function<double()>), std::function<double()>&, std::_Bind<double (*(std::function<double()>, std::function<double()>))(std::function<double()>, std::function<double()>)> >::type {aka std::_Bind<double (*(std::function<double()>, std::_Bind<double (*(std::function<double()>, std::function<double()>))(std::function<double()>, std::function<double()>)>))(std::function<double()>, std::function<double()>)>}’ to non-scalar type ‘doubleFunc {aka std::function<double()>}’ requested
Kuba Wyrostek
  • 6,163
  • 1
  • 22
  • 40
  • I kinda wish they didn't vote [the composition functionality](http://stackoverflow.com/questions/25841857/vc2013-function-from-bind-not-compiling/25842919#25842919) of `bind` into the standard... – T.C. Jan 20 '15 at 11:33
  • Just to clarify (since the question was closed): so the composition of `std::bind` call in commented-out line works as if `add()` was expecting result of function (here: double) instead of function object itself, is that correct? – Kuba Wyrostek Jan 20 '15 at 12:31
  • Yes, that's correct. – T.C. Jan 20 '15 at 14:31

0 Answers0