使用带有 tr1 服务包和英特尔 C++ 编译器 11.1.071 [IA-32] 的 Visual Studio 2008,这与我的另一个问题有关
我正在尝试为 c++ 编写一个功能映射,它的工作方式有点像 ruby 版本
strings = [2,4].map { |e| e.to_s }
所以我在 VlcFunctional 命名空间中定义了以下函数
template<typename Container, typename U>
vector<U> map(const Container& container, std::tr1::function<U(Container::value_type)> f)
{
vector<U> transformedValues(container.size());
int index = -1;
BOOST_FOREACH(const auto& element, container)
{
transformedValues.at(++index) = f(element);
}
return transformedValues;
}
你可以这样调用它(注意函数模板参数是显式定义的):
vector<int> test;
test.push_back(2); test.push_back(4);
vector<string> mappedData2 = VlcFunctional::map<vector<int>,string>(test, [](int i) -> string
{
return ToString(i);
});
或者像这样(注意函数模板参数没有明确定义)
std::tr1::function f = [](int i) -> string { return ToString(i); };
vector<string> mappedData2 = VlcFunctional::map<vector<int>,string>(test, f);
但至关重要的是,不喜欢这样
vector<string> mappedData2 = VlcFunctional::map(test, [](int i) -> string { return ToString(i); });
如果没有明确定义 hte 模板参数,它不知道要使用哪个模板,并且会因编译错误而崩溃
..\tests\VlcFunctional_test.cpp(106): error: no instance of function template "VlcFunctional::map" matches the argument list, argument types are: (std::vector<int, std::allocator<int>>, __lambda3)
必须定义模板参数使其语法变得更加庞大,我的目标是在调用站点上尽量减少麻烦——关于为什么它不知道如何进行转换的任何想法?这是编译器问题还是语言不允许这种类型的模板参数推断?