6 ms·
It's only an oxymoron according to folk wisdom. The common shorthand definitions of constexpr and virtual are both too simple. People come to believe that const
by jeffbee 5y ago
It's only an oxymoron according to folk wisdom. The common shorthand definitions of constexpr and virtual are both too simple. People come to believe that constexpr means evaluated by the compiler, but it really means that it may be evaluated by the compiler. Similarly, programmers believe that virtual means vtable dispatch, but all it really means is the function supports dynamic dispatch. It may be de-virtualized at compile time, or there may be no overrides anywhere in the program.
If you understand the true definitions `constexpr virtual` doesn't seem contradictory.
- mshockwave 5y agoI dunno why people downvote this comment, it seems legit and it's important to know that `inline`, `virtual`, and `constexpr` are actually just heuristics / suggestions to compilers.
- jeffbee 5y agoInline is probably the keyword with true definition furthest from popular belief. By the way, constexpr implies inline, for function declarations.
- jcelerier 5y ago> it seems legit and it's important to know that `inline`, `virtual`, and `constexpr` are actually just heuristics / suggestions to compilers. but they are not ? - inline relaxes ODR which generally changes the linkage of the symbol (weak linkage when inline & exported, strong when not) - adding virtual will always make your class have a vtable and your method overridable. - constexpr make it possible to use in e.g. template arguments: constexpr int foo() { return 123; } std::array<int, foo()> arr; that does not mean that the compiler cannot optimize - no matter how complex your program is, if the compiler has sufficiently advanced optimization passes, it should be able to precompute everything that is possible at compile time
- jeffbee 5y ago> adding virtual will always make your class have a vtable No? https://godbolt.org/z/qMzY1h6Gs https://godbolt.org/z/qMzY1h6Gs
- adamrezich 5y agowow, I never knew that, crazy
- jeffbee 5y agoThis example is trivial but compilers are generally very good at de-virtualizing at compile time even in large programs. People who bring up the supposed cost of vtable dispatch are usually either repeating bad folk wisdom, or haven't used the language since 20 years ago.
- adamrezich 5y agoseems to me like the real problem is the burden of knowledge required to intuit how C++ compilers will or won't optimize the code you write. I know this has been an ongoing refrain for years now but this sort of thing has driven me away from using C++ personally. I wish there was a better syntactic system for denoting where you do and don't want certain optimizations to be applied.
- jcelerier 5y agodo you also wonder where the JVM or .net runtime will inline method calls ?
- adamrezich 5y agono because those are explicitly "Managed" systems
- jcelerier 5y ago