Question

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()?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top