c++ - 多重转换规则 C++

标签 c++ templates

在下面的代码中,

    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/

相关文章:

c++ - 运算符重载为友元函数

django - 在 django blocktrans 中使用 'now'?

c++ - 将函数作为模板参数传递

c++ - 编译器报告 'deleted' operator = ,但它在那里

c++ - 使用多个源文件时,GDB 不会中断某些代码行

c++ - 为什么在段错误中通过 B 类中的方法初始化 A 类的指针?

c++ - 类模板特化中的成员函数语法

c# - Visual Studio 服务引用的自定义模板?

c++ - 如何在 Qt 中翻转图像?

c++ - 获取属于给定整数的颜色