1
votes
#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

2
That's not how templates work. Your template parameters are classes, or typenames, not ints.Sam Varshavchik
@SamVarshavchik What if I wanted to specify that both parameters will be ints? Obviously, I could just create a standard function, but can it be done using templates?asymmetryFan
Since T is not a type, foo can't be function. Thus, it must be a variable, and void is not a valid type for a variable. (Note that template<int T> int variable(T); is a valid declaration in C++14.)molbdnilo
@grizloni97 If you want to specify that both parameters are int, you shouldn't use a template function.molbdnilo
If you want both parameters to be int you just declare an ordinary function with two int parameters. That's it. That's what ordinary functions are for. This is not what templates are for.Sam Varshavchik

2 Answers

4
votes

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) {
}
2
votes

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