Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is practical difference between `inline` and `template<class = void>`?

Tags:

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?

like image 440
Vitalii Avatar asked Nov 15 '18 09:11

Vitalii


People also ask

What is void inline function?

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.

What is inline void in C++?

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.

What are the advantages of inline function over normal function?

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.


1 Answers

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

like image 135
user7860670 Avatar answered Sep 18 '22 04:09

user7860670