We have 2 methods to declare function in header-only library. They are inline
and template<class = void>
. In boost
source code I can see both variants. Example follows:
inline void my_header_only_function(void) { // Do something... return; } template<class = void> void my_header_only_function(void) { // Do something... return; }
I know what is difference according to C++ standard. However, any C++ compiler is much more than just standard, and also standard is unclear often.
In situation where template argument is never used and where it is not related to recursive variadic template, is there (and what is) practical difference between 2 variants for mainstream compilers?
Its code is just intertwined seamlessly with the code it's called from. So, if you take the address of a function (e.g. to assign to a pointer) then the compiler has to generate it as a real function, and cannot inline it. void means the function does not return a value.
Inline function is a function that is expanded in line when it is called. When the inline function is called whole code of the inline function gets inserted or substituted at the point of inline function call. This substitution is performed by the C++ compiler at compile time.
Advantages :- 1) It does not require function calling overhead. 2) It also save overhead of variables push/pop on the stack, while function calling. 3) It also save overhead of return call from a function. 4) It increases locality of reference by utilizing instruction cache.
I think this can be used as a weird way to allow library extension (or mocking) from outside library code by providing specialization for void
or a non-template version of the function in the same namespace:
#include <iostream> template<class = void> int foo(int data) { ::std::cout << "template" << std::endl; return data; } // somewhere else int foo(int data) { ::std::cout << "non-template" << std::endl; return data; } int main() { foo(1); // non template overload is selected return 0; }
online compiler
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With