开发者

Why is the static keyword needed in this template code?

开发者 https://www.devze.com 2023-04-06 21:45 出处:网络
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 wil

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


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


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号