arguments in templates

Can anybody point out what is wrong with the following code:

header file Header.h:
1
2
3
4
5
template<typename T,typename B,typename C>
T add(B a,C b){
T ab = a+b;
    return ab;
}


main.cpp file :
1
2
3
4
5
6
7
8
9
#include <iostream>
#include "Header.h"

int main()
{
    add(10, 20);
    
    return 0 ;
}


i get the error : "no matching function to call add?" in the main file

but this runs fine :

1
2
3
4
template<typename T>
T add(T a,T b){
    return a+b;
}


Your function template has three type template parameters: T, B, and C. You've given the compiler enough information to figure out B (your first function argument's type is int, so B must be int) and C (your second argument's type is int, so C must be int), but not enough to figure out T. What should it return? int? what if a+b doesn't fit in an int? long? long long?

In C++98, provide the argument:

1
2
3
4
int main()
{
    add<int>(10, 20);
}


In C++11, you can calculate the return type from the parameter types:

1
2
3
4
5
6
template<typename B, typename C>
auto add(B a,C b) -> decltype(a+b)
{
    auto ab = a+b;
    return ab;
}


in C++14, you can let the compiler do that

1
2
3
4
5
6
template<typename B, typename C>
auto add(B a,C b)
{
    auto ab = a+b;
    return ab;
}
what if the user does not know the types and number of arguments he want in the function he is going to create :

for example
1
2
3
4
5
template<typename X, typename A, typename B>
class Foo {

int add(X x, A a, B b, C c) // and soo on …maybe 10 or more?
}

does the person have to explicitly write typename C or is there a shortcut to have unlimited number of arguments in line 1;
Perhaps variadic template is what you want.
http://en.wikipedia.org/wiki/Variadic_template
Here's a quick example (it doesn't use perfect forwarding though):
http://coliru.stacked-crooked.com/a/04b1f0ca1439fc38
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

template<typename Last>
auto add(Last last)
{
    return last;
}
template<typename First, typename... Rest>
auto add(First first, Rest... rest)
{
    return first + add(rest...);
}

int main()
{
    std::cout << add(1) << std::endl;
    std::cout << add(1, 2) << std::endl;
    std::cout << add(1, 2, 3) << std::endl;
    std::cout << add(1, 2, 3, 4) << std::endl;
}















1
3
6
10
The order of the templates is important - if you swapped which came first it would not compile.
Last edited on
Topic archived. No new replies allowed.