ar-org-austral
ar-org-austral

Reputation: 21

C++ Inline functions and template function in header-only library

In order to avoid code bload due to over-inlining...
Is this a valid way to implement a template function that acts like an inline function?

Original inline function declaration:

inline double MyInlineFunction(){
        return 3.141592653589;
}

Alternative function declaration using template function:

template<typename T = void> double MyInlineFunctionT(){
    return 3.141592653589;
}

Upvotes: 2

Views: 2353

Answers (1)

Pete Becker
Pete Becker

Reputation: 76245

Marking a function inline tells the compiler that it's okay to have the same function defined in more than one translation unit. It's also a hint that the function ought to be expanded inline, but most compilers make their own judgment in that regard. Similarly, a template function can be instantiated in more than one translation unit, and compilers will make their own judgment as to whether to expand it inline.

Short version: there's no difference in code size. But the template version is harder to understand, harder to compile, harder to use, and more likely to produce errors.

Upvotes: 3

Related Questions