【问题标题】:template function why can't add "cin"?模板函数为什么不能加“cin”?
【发布时间】:2017-08-26 01:30:39
【问题描述】:
#include <iostream>
using namespace std;

template<int x, int y> 
void add()
{
    cin >> x >> y;
    cout << x + y << endl;
}

int main()
{
    add<1,2>();

    return 0;
}

在Windows10 + Visual Studio 2017中,报错:Binary >> : the operator of the leftoperands of the STD: : istream type is not found(或没有可接受的转换)

参数xy 与其他普通的int 变量有什么不同?

【问题讨论】:

  • 如果你在没有模板的情况下尝试这个,你会得到同样的错误。为您准备的一些 Google 食物:“运算符优先级”。
  • @SamVarshavchik:您的意思是用常规函数参数替换模板参数?不,在这种情况下不会出错(尽管参数毫无意义,因为函数会立即覆盖它们)。
  • 如果您遇到错误,请将错误消息放在您的问题中。
  • xy 不是变量。它们是模板参数。将新值读入常量 1 和 2 意味着什么?

标签: c++ templates


【解决方案1】:

是的,模板参数与普通函数参数不同。模板参数是编译时常量。鉴于您对add 模板的定义,当您使用add&lt;1,2&gt; 对其进行实例化时,编译器实际上会创建如下函数:

// where 'function_name' is a compiler generated name which is
// unique for the instantiation add<1,2>
void function_name()
{
    cin >> 1 >> 2;
    cout << 1 + 2 << endl;
}

显然,你不能这样做:

cin >> 1 >> 2;

您需要输入实际的可修改对象,而不是常量。

【讨论】:

    【解决方案2】:

    我想你想要更多这样的东西:

    #include <iostream>
    using namespace std;
    
    template<class T>
    void add(T x, T y)
    {
        cin >> x >> y;
        cout << x + y << endl;
    }
    
    int main()
    {
        add(1, 2);
    
        return 0;
    }
    

    在您的示例中,xy 是模板参数,但您试图在您的 cincout 语句中将它们用作值。

    【讨论】:

      猜你喜欢
      • 2019-11-16
      • 1970-01-01
      • 2016-02-25
      • 2021-09-25
      • 2011-07-03
      • 2011-08-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多