简体   繁体   中英

template function why can't add “cin”?

#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;
}

In Windows10 + visual studio 2017 , it gets an error : Binary > > : the operator of the left operands of the STD: : istream type is not found (or there is no acceptable conversion)

The parameter x and y is something different from other normal int variables?

I think you want something more like this:

#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;
}

In your example, x and y are template parameters, yet you're trying to use them as values in your cin and cout statements.

Yes, template parameters are different than normal function parameters. Template parameters are compile time constants. Given your definition of the add template, when you instantiate it with add<1,2> , the compiler essentially creates a function like this:

// 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;
}

Obviously, you can't do this:

cin >> 1 >> 2;

You need actual modifiable objects to input into, not constants.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM