1

I have read following questions:

  1. Template functors vs functions
  2. C++ Functors - and their uses
  3. C++ function template partial specialization?

And I understand what C++ functors are good for. But I can't deduce what will happen if will do the following:

template <typename T, unsigned int state>
class Foo {
public:
    static Foo_func() { /* Do something */ };
}

// Partial specialization:
// -- state == 1
template <typename T>
class Foo <T, 1> {
public:
    static Foo_func() { /* Do something */ };
}

template <typename F>
void call_func(F func) {

    // Do something... //

    func();

    // Do something... //
}

int main() {
    Foo <double, /*state*/ 1> obj;

    // Case 1:
    call_func(obj.Foo_func);

    // Case 2:
    call_func(Foo<double, /*state*/ 1>::Foo_func);
}

In which scenario compiler will be able to inline Foo_func() ?

Community
  • 1
  • 1
PatrykB
  • 1,579
  • 1
  • 15
  • 24
  • 1
    Look at the assembly and see what the compiler does. A good resource to use is https://gcc.godbolt.org/ – NathanOliver Apr 25 '17 at 11:53
  • Your code doesn't compile for a lot of reasons. For what it's worth, the compiler should be able to inline the calls to `func`, but I suspect it will only do so if `call_func` itself is inlined. [In this simple code the compiler inlines everything](https://godbolt.org/g/8KmlTv). – Cornstalks Apr 25 '17 at 11:56
  • 1
    You can't reliably deduce optimizations in general, always check the asm. FWIW Clang and GCC both inline these in this case, but they might not always do it. – harold Apr 25 '17 at 11:58
  • btw, `functor`'s are function object. A class with `operator()()` overloaded. You have tagged the question with functor. but all you are using function pointer. Also note that you don't need to instantiate an object of a class to use a `static` member function. – army007 Apr 25 '17 at 12:13

1 Answers1

5

But I can't deduce what will happen if will do the following

It's not possible to deduce what will happen, you just have to try it and see.

Inlining is an optimization, not a language feature. When and whether it happens depends on your compiler, its version, how you configure it, and possibly lots of other context around the (possibly in-lined) call site.

Useless
  • 64,155
  • 6
  • 88
  • 132