0

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

Casey
  • 41,449
  • 7
  • 95
  • 125
Edward
  • 235
  • 4
  • 18

1 Answers1

2

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.

Mat
  • 202,337
  • 40
  • 393
  • 406
  • I thought as much. So are there no down sides to using the static functions method? (Assuming the class has no member variables) – Edward Dec 11 '13 at 09:54
  • If by "using the static functions method" you mean the call `B::foo()` then no. Your argument that it makes the class "harder to understand" doesn't really make sense. Putting a `ptr->foo()` instead when it is intended to be a static call would "obfuscate" the template. – Mat Dec 11 '13 at 10:18