【问题标题】:Where shoud I fix a C++ code about the template?我应该在哪里修复有关模板的 C++ 代码?
【发布时间】:2017-08-21 22:17:26
【问题描述】:

当我写了一段 C++ 代码并通过 clang++ 编译器编译时,

error: expected expression
template <typename T>
^

被代表了。

为什么会出现这个错误,我该如何解决?

#include<iostream>
using namespace std;

int main() {

template <typename T>
T sum(T a, T b) {
return a+b;
}

cout <<"Sum = " << sum( 2.1, 7.9 ) << endl;

return 1;
}

【问题讨论】:

    标签: c++ templates clang++ expected-exception


    【解决方案1】:

    您不能在main 中定义函数。将定义移到外面

    #include <iostream>
    
    template <typename T>
    T sum(T a, T b)
    {
        return a + b;
    }
    
    int main()
    {
        std::cout << "Sum = " << sum(2.1, 7.9) << std::endl;  
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-08
      • 1970-01-01
      • 1970-01-01
      • 2012-01-17
      • 1970-01-01
      相关资源
      最近更新 更多