ubbdd
ubbdd

Reputation: 241

Why is the static keyword needed in this template code?

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

Upvotes: 1

Views: 180

Answers (2)

Oscar Korz
Oscar Korz

Reputation: 2487

C::work(a, b) names a static member function work() of class C.

Upvotes: 3

templatetypedef
templatetypedef

Reputation: 373052

The reason that static is required here is that in the compare template function, you have this line:

return C::work(a, b);

The syntax C::work(a, b) here means "call the function work nested inside the class C. Normally, this would try to call a member function without providing a receiver object. That is, typically the way you'd call a function work would be by writing

C myCObject;
myCObject.work(a, b);

In this case, though, we don't want to be calling a member function. Instead, we want the function work to 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 functions static so that they can be called like regular functions.

Hope this helps!

Upvotes: 1

Related Questions