请考虑以下代码片段:
#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