Working on a simple example for template functions. The code compiles and works as expected. But my question is why “static” is required in both “Cmp” and “Lit”? Otherwise, it will not compile?
Thanks a lot!
template<class T> class Cmp{
public:
static int work(T a, T b) {
std::cout << "Cmp\n";
return 0;
}
};
template<class T> class Lit{
public:
static int work(T a, T b){
std::cout << "Lit\n" ;
return 0;
}
};
template<class T, class C>
int compare(const T &a, const T &b){
return C::work(a, b);
}
void test9(){
compare<double, Cmp<double> >( 10.1, 20.2);
compare<char, Lit<char> >('a','b');
}
The reason that
staticis required here is that in thecomparetemplate function, you have this line:The syntax
C::work(a, b)here means “call the functionworknested inside the classC. Normally, this would try to call a member function without providing a receiver object. That is, typically the way you’d call a functionworkwould be by writingIn this case, though, we don’t want to be calling a member function. Instead, we want the function
workto be similar to a regular function in that we can call it at any time without having it act relative to some other object. Consequently, we mark those functionsstaticso that they can be called like regular functions.Hope this helps!