简体   繁体   中英

Scope Resolution to a Static Function or a Pointer in Template Class

I'm currently working on some code that someone else has written and I'm unsure of the efficiency of their method. They have a template class that uses scope resolution to access the class's members instead of having a pointer to the templatised class and accessing it that way. For example:

template <typename T>
class A {
    void func() {
        T::DoSomething();
    }
};

class B {
    static void DoSomething() {
        // code...
    }
};

I personally feel it makes the template class hard to understand, but my main area of query is the performance. Which is more efficient; using a scope resolution, or having a private member variable A::T* p_blah and calling B 's function using p_blah->DoSomething() ?

Scope resolution is something that happens entirely at compile time. The method used in that code results in a direct, inlinable, function call. You can't really beat that.

Your proposal:

  • Requires an instance of B to be created somehow
  • Requires that a pointer to that instance either be stored in A (increasing its size) or in a global (always problematic)
  • Introduces the need to track that instance's lifetime

In short it has little chance of being as efficient as what you currently have.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM