templates confusion

I guess i am still trying to understand templates. One thing i dont understand is if i am using a string for example, i have to define <std::string> for is_in(), whereas if i am using an int or char, i can just call is_in() without <>, and it figures what is being sent in. I guess i dont understand why some need defining and others do not?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 
#include <iostream>
#include <vector>

template<class T>
bool is_in(T val, std::vector<T> container){
    for (auto i:container){
        if (val == i){
            return  true;
        }
    }
    return false;
}

int main(){
    std::vector<std::string> v = {"test", "TEST"};
    std::cout << is_in<std::string>("test", v);
    std::cout << is_in<std::string>("tester", v);
    //std::cout << is_in("tester", v);
    
    
    std::vector<char> v2 = {'a','b'};
    std::cout << is_in('a', v2);
    std::cout << is_in('z', v2);
}
Last edited on
for function templates, the compiler can deduce the template parameters from the function arguments, but only if they can match pretty much exactly The type of the argument "test" is const char[5], but the type of v is vector<string>. There is no T for which is_in<T> would take arguments with those types.

try is_in(std::string ("test"), v)
ooooooooh ok,
thanks
Topic archived. No new replies allowed.