In C ++, is there a way to have an “abstract” method of the base class (that is, declared and called from the base class, but implemented in subclasses) without declaring the method as virtual ?
This question, of course, applies only to cases where polymorphism is not needed (pointers / references to basic types have never been used). Consider the following:
#define NO_OPT asm volatile ("");
Note that in this case polymorphism is not necessary and that there are many optimization possibilities for the compiler.
However, I checked this code in the latest g++ (4.8.2) and clang (3.4) with -O3 optimizations turned on, including binding time (LTO), and it was significantly slower than the following: alternative implementation (using templates instead of the virtual method):
namespace test2 { template<typename DerivedType> struct Base : public DerivedType
g++ and clang were remarkably consistent, each of which constituted optimized code that took 9 seconds to complete the test1 loop, but only 3 seconds to complete the test2 loop. Therefore, even if the test1 logic does not need to be dynamically dispatched, since all calls must be resolved at compile time, it is still much slower.
So, to repeat my question: If polymorphism is not needed, is there a way to achieve this “abstract method” behavior using convenient direct class inheritance (for example, in test1 ), but without degrading the performance of virtual functions (as achieved in test2 )?
source share