请考虑以下代码段:
#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));
}
为什么在最后(注释掉)的行中调用doubleFunc
时第三个参数需要转换为std::bind
?
这是GCC 4.8编译错误:
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