我正在阅读C++ 模板:完整指南,在第 4 章(4.2 非类型函数模板参数)中是模板函数的示例,可与 STL 容器一起使用,为集合的每个元素添加值。这是完整的程序:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
template<typename T, int VAL>
T addValue(T const& x)
{
return x + VAL;
}
int main()
{
std::vector<int> source;
std::vector<int> dest;
source.push_back(1);
source.push_back(2);
source.push_back(3);
source.push_back(4);
source.push_back(5);
std::transform(source.begin(), source.end(), dest.begin(), (int(*)(int const&)) addValue<int, 5>);
std::copy(dest.begin(), dest.end(), std::ostream_iterator<int>(std::cout, ", "));
return 0;
}
我不得不做出那个丑陋的演员,因为这本书说:
Note that there is a problem with this example: addValue<int,5> is a function template, and function templates are considered to name a set of overloaded functions (even if the set has only one member). However, according to the current standard, sets of overloaded functions cannot be used for template parameter deduction. Thus, you have to cast to the exact type of the function template argument:
std::transform (source.begin(), source.end(), // start and end of source
dest.begin(), // start of destination
(int(*)(int const&)) addValue<int,5>); // operation
我的问题是运行程序时出现分段错误。我在 Mac 上使用 Clang 构建它。
演员表不正确还是问题可能是什么?