汽车不能';t推断std::function的类型 我在C++中实现Python的映射(以比代码STD::变换< /C> >更有效的方式:
如何使编译器推理为我自己的类型,以便汽车不能';t推断std::function的类型 我在C++中实现Python的映射(以比代码STD::变换< /C> >更有效的方式:,c++,functional-programming,c++17,C++,Functional Programming,C++17,如何使编译器推理为我自己的类型,以便 auto f = [](const int& x) {return x*x;}; auto squared = fmap(f, vec_test); 或者更简单: auto squared = fmap([](const int& x) {return x*x;}, vec_test); 一种方法不是使用std::function作为参数,而是使用一个简单的模板,并使用auto推断返回类型。这可能是将实际代码简化为最小示例的产物,但在这
auto f = [](const int& x) {return x*x;};
auto squared = fmap(f, vec_test);
或者更简单:
auto squared = fmap([](const int& x) {return x*x;}, vec_test);
一种方法不是使用std::function作为参数,而是使用一个简单的模板,并使用auto推断返回类型。这可能是将实际代码简化为最小示例的产物,但在这里使用
std::function
是完全没有意义的。lambda已经是一个函数,它接受const int&
并返回int
;没有必要强迫它使用那种类型autof=[](const int&x){return x*x;}
可以正常工作。跳过<代码> f<代码>,只调用lambda作为第一个参数,就可以调用<代码> fMAP>代码>一个建议:不必使用func
参数设置为fmap
裸模板参数,则fmap
将能够直接获取lambda函数,而无需std::function
wrapper@hegel5000你能详细说明一下吗?试试这个模板自动fmap(F func,const std::vector&vec){TypeIn x;使用TypeOut=decltype(func(x));std::vector result;std::transform(vec.begin(),vec.end(),std::back_inserter(result),func);返回std::move(result);}
auto f = [](const int& x) {return x*x;};
auto squared = fmap(f, vec_test);
auto squared = fmap([](const int& x) {return x*x;}, vec_test);