作为一个练习(注意,我知道std :: transform),我试图实现通常在函数式语言上找到的映射函数,例如C++中的Haskell 。这是我的代码:g ++无法推断功能图实现的模板类型
#include <iostream>
#include <vector>
#include <functional>
template<typename A, typename B>
std::vector<B> functional_map (std::function<B(A)> func, std::vector<A> v)
{
std::vector<B> result(v.size());
for(int i = 0; i < v.size(); ++i) {
result[i] = func(v[i]);
}
return result;
}
尽管如此,当这样调用编译器无法正确推断functional_map模板类型:
int square (int x) {return x*x;}
int main()
{
std::vector<int> v = {1,2,3,4,5,6,7,8,9,10};
std::vector<int> v2 = functional_map(square, v);
for (int y : v2) {
std::cout << y << " ";
}
}
这是G ++所产生的错误:
functional_cpp.cpp: In function ‘int main()’:
functional_cpp.cpp:18:35: error: no matching function for call to ‘functional_map(int (&)(int), std::vector<int>&)’
vector<int> v2 = functional_map(square, v);
^
functional_cpp.cpp:6:44: note: candidate: template<class A, class B> std::vector<B> functional_map(std::function<B(A)>, std::vector<A>)
template<typename A, typename B> vector<B> functional_map (function<B(A)> func, vector<A> v) {
^
functional_cpp.cpp:6:44: note: template argument deduction/substitution failed:
functional_cpp.cpp:18:35: note: mismatched types ‘std::function<B(A)>’ and ‘int (*)(int)’
vector<int> v2 = functional_map(square, v);
显然,克++失败以匹配正则函数指针std::function
类型,它是由使所有功能一致的打字在C++中。请注意,由拉姆达改变方也没有编译(但类型正在对变化相匹配,从nt (&)(int)
到lambda(int)
。
话虽这么说,改变functional_map
到functional_map<int, int>
编译成功,并用正确的结果执行。
这是为什么发生了什么?我怎样才能解决我的实现,因此编译器会推断出模板类型?
编辑为了避免混淆std::map
,作为意见建议我在更名“地图”与“functional_map”所有问题
'使用namespace std'并声明像'map'和'list'这样的名字似乎是灾难的秘诀。已经停止滥用命名空间,并且无论谁告诉你几次在头部周围说'使用命名空间标准'。 –
@KerrekSB我很清楚这一点,感谢您的反馈。正如我在文章中提到的那样,这是一个快速练习,所以我并不打扰stl友好,我只是想避免输入std ::一堆,如果必须的话,把它当作肮脏的黑客。无论如何,也许我应该改变我的问题,不要混淆未来的读者? – Setzer22
我并没有因为对* meducating *用户的困惑而迷惑读者。想想那些在你的帖子中发生的可怜的无辜者,并且他们的可塑性大脑中植入了更多的潜意识信息,这是可以接受的代码... –