在下面的代码中,
std::transform (source.begin(), source.end(), // start and end of source
dest.begin(), // start of destination
(int(*)(int const&)) addValue<int,5>); // operation
有人可以分解类型转换吗,
(int(*)(int const&))
其中 addValue 是非类型函数模板给出的
template <typename T, int VAL>
T addValue (T const& x)
{
return x + VAL;
}
谢谢。
最佳答案
Actor (int(*)(int const&))
是类型 int(*)(int const&)
的转换,这是“指向函数的指针采用 int const&
并返回 int
”的类型。
自 addValue<int, 5>
已经具有“采用 int const&
并返回 int
的函数”类型(并且在按值传递时将衰减为函数指针),在此上下文中不需要强制转换。
此类转换何时有用的一个示例是消除具有相同名称的多个函数模板之间的歧义。如果,除了addValue
显示的定义,我们也有这个:
template <typename T, int VAL>
void addValue(T& x) {
x += VAL;
}
然后指定 addValue<int, 5>
单独会是模棱两可的。告诉编译器什么类型 addValue
应该在实例化后告诉它使用 int addValue<int, 5>(int const&)
而不是 void addValue<int, 5>(int&)
, 所以它会知道选择哪个模板。
关于c++ - 多重转换规则 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40198810/