简体   繁体   中英

Template function declared as void - code doesn't work?

#include <iostream>
#include <string>

template<int T, int U>
void foo(T a, U b)
{
    std::cout << a+b << std::endl;
}

int main() {
    foo(2,4);
    return 0;
}

I get the following errors:

error: variable or field 'foo' declared void

error: expected ')' before 'a'

error: expected ')' before 'b'

In function 'int main()': error: 'foo' was not declared in this scope

Your T and U in your template are not types. You need to change it to:

template<typename T, typename U>
void foo(T a, U b) {
}

Template parameters can be integers, for example:

template<int A, int B>
void bar()
{
    std::cout << A+B << std::endl;
}

However, it seems like you want to parametrize your method on the types of the parameters, not on integer values . The correct template would be this:

template<typename T, typename U>
void foo(T a, U b)
{
    std::cout << a+b << std::endl;
}

int main() {
    bar<2,4>();
    foo(2,4);     // note: template parameters can be deduced from the arguments
    return 0;
}

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