1

Considering the fact that a pointer to a function returning another pointer to another function is the mechanism used in C to introduce some runtime polymorphism/callbacks, What is the equivalent way to implement this in C++ while improving locality and lower the cost about pointers and indirections ?

For example this syntactic sugar can help but I'm not really interested in this, altough it's a nice way to do things in a C++ way instead of a more C-ish typedef, I'm more interested in improving locality while trying to reduce the use of explicit pointers at runtime.

Community
  • 1
  • 1
user2485710
  • 9,451
  • 13
  • 58
  • 102
  • What are you trying to do? Show us the old way (code) of doing this. We cannot improve things based on guessing. – user694733 Nov 21 '13 at 08:01
  • @user694733 I'm not adding any specific example because this will polarize the discussion, I'm not expecting any piece of code from other users, this question is more about the design and the performance rather than actual code. – user2485710 Nov 21 '13 at 08:25
  • Performance is always tied to the specific application. There are no universal guides: *"Do X and it will be always faster"*. For your problem virtual functions seem like way to go. In my experience, the flexibility they provide has always been bigger factor than the neglible performance cost. If you want to improve things like branch prediction, you need to show the exact problem first, because the answer will depend on that. – user694733 Nov 21 '13 at 09:39

2 Answers2

3

The real reason as to why people use function pointers in C to emulate polymorphism is not performance but the fact that C neither supports real polymorphism nor templates. These are two alternatives you have in C++. All three approaches are compared in this thread.

Note that even though calling a function pointer does not require the additional vtable lookup that virtual function calls do, calling virtual functions and function pointers both suffer from the same major performance problem: Branch prediction in both cases is not as reliable and you tend to end up with more pipeline flushes.

Community
  • 1
  • 1
Domi
  • 22,151
  • 15
  • 92
  • 122
  • That's what I'm trying to do, I'm trying to help the CPU with locality. – user2485710 Nov 21 '13 at 08:23
  • As pointed out in [the linked thread](http://stackoverflow.com/questions/1955074/virtual-methods-or-function-pointers), you get the best performance by using templates. But in most cases, it is not worth the disadvantages that result from it. The worst about using templates are [cryptic compiler errors](http://programmers.stackexchange.com/questions/70086/why-are-c-template-error-messages-so-horrific). – Domi Nov 23 '13 at 04:29
0

I think you can use Virtual function for meet part of the requirement.

thinkinnight
  • 141
  • 1
  • 1
  • 6