I wrote a template to have a valid usage only when a struct, class has overloaded bool operator== otherwise compiler errors would come up,
namespace atn {
template <typename T>
bool find( std::vector<T>& cont, T find ) {
for( std::vector<T>::iterator it = cont.begin(); it != cont.end(); ++it ) {
if( (*it) == find )
return true;
}
return false;
}
};
So fine it is ok, for example:
struct sPlayer {
u_int idPlayer;
sPlayer() : idPlayer(0) {};
bool operator==( const sPlayer& ref ) const {
return ref.idPlayer == this->idPlayer;
};
};
int _tmain(int argc, _TCHAR* argv[]) {
std::vector<sPlayer>a;
sPlayer player;
player.idPlayer = 5;
a.push_back(player);
if(atn::find(a, player)){
std::cout << "Found" << std::endl;
}
return 0;
}
The thing is, if I use it this way:
vector<int>hold;
if(atn::find(hold, 4))
I got lost at this part, the templates assumes the type of T to be assigned at vector<T> by the value of the second parameter passed? Or it’ll assume from the type of the vector reference passed?
Both arguments have to match. Template argument deduction tries to find a type for each template argument that makes the function argument types match the type of the supplied arguments.
Sometimes this gets a bit tricky, and things that should work don’t. For example:
This fails, because the first argument wants to deduce
T = int, but the second argument wantsT = unsigned int. The deduction fails and the code doesn’t compile. (If this is a problem, then the solution is to make all but one function argument non-deduced.)