c++ - 函数模板无法编译

标签 c++ templates

我正在学习函数模板,但我在下面创建的模板无法编译,我不确定哪里出了问题。我试图让一个 int 变量和一个 double 变量进入模板,但是当我调用函数时我总是收到错误。错误是:

error: no matching function for call to 'LargestFunction(int&, double&)'|

代码如下:

 template <class Temp>
    Temp LargestFunction(Temp a, Temp b){
        if(a > b){
            return a;
        }
    else
        return b;
    }

    int main()
    {
        int NumOne = 30;
        double NumTwo = 52.252;
        cout << LargestFunction(NumOne,NumTwo);
        return 0;
    }

最佳答案

  1. 如果要支持不同的类型,需要定义不同模板参数的模板。

    template <typename Lhs, typename Rhs>
    typename std::common_type<Lhs, Rhs>::type max(const Lhs &lhs, const Rhs &rhs) {
      return lhs > rhs ? lhs : rhs;
    }
    

    这样你就可以传递不同的类型,你会得到它们之间的共同类型。

  2. 如果您只想处理函数内的相同类型,您可以保持模板不变。

    template <typename T>
    T max(const T &lhs, const T &rhs) {
        return lhs > rhs ? lhs : rhs;
    }
    

    然后您需要强制转换其中一个参数,以便拥有相同的类型。

    max(static_cast<double>(101), 4.2);
    

    或者,您也可以显式特化函数模板,但通常不鼓励这样做。

    max<double>(101, 4.2);
    

关于c++ - 函数模板无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20602831/

相关文章:

c++ - 错误 C2146 : syntax error : missing ';' before identifier 'g_App'

c++ - 函数模板 : clang rejects, gcc 接受的从属名称查找

c++ - 使用默认参数转发引用?

templates - Grails:将 taglib 中的模板渲染为 HTML

html - FreeMarker模板中字符串过长如何灵活调整列宽?

c++ - 快速登录 C++ float...此代码中是否存在任何平台依赖性?

c++ - 当树莓派终端上的更新时间时,QT 上的 exe 文件挂起

c++ - QTimer 不会前进屏幕

c++ - 如何将字符串转换为打开以供读取的 FILE*

c++ - 将不同枚举类类型作为输入的函数,怎么样?