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

Viewed 1168

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?

3 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

One difference is that binary code for the function may become part of the generated object file even if the function is never used in that file, but there will never be any code for the template if it's not used.

I'm the author of Beast. Hopefully I will be able to shed some light on why you see one versus the other. It really is very simple, the template seems less likely to be inlined into calling functions, bloating the code needlessly. I know that "inline" is really only supposed to mean "remove duplicate definitions" but sometimes compiler implementors get overzealous. The template thing is a little bit harder on the compile (Travis craps out sometimes at only 2GB RAM). So I decided to try writing some new stuff using the "inline" keyword. I still don't know how I feel about it.

The short answer is that I was doing it one way for a long time and then I briefly did it the other way for no particularly strong reason. Sorry if that is not as exciting as the other theories! (which were very interesting in fact)

Related