Inline Keyword with Templates
When considering the usage of the inline keyword with templates, the question arises whether it is redundant, given the compiler's ability to determine the benefits of inlining.
The Answer: No, It's Not Irrelevant
Despite the compiler's knowledge, the inline keyword remains relevant for templates. While function templates are generally not inline by default, their explicit specialization can make them inline.
Specific Cases
There are instances where omitting the inline keyword can lead to issues. Consider the following example:
#include "tpl.h"
#include "tpl.h"
#ifndef TPL_H #define TPL_H template<class T> void f(T) {} template<class T> inline T g(T) {} template<> inline void f<>(int) {} // OK: inline template<> int g<>(int) {} // error: not inline #endif
Compiling this code results in multiple definition errors because g<> is not explicitly marked as inline.
Rule of Thumb
To maintain consistency and avoid potential errors, consider using the inline keyword for function templates that are intended to be inline. This aligns with the proposed rule of thumb in Vandevoorde's/Josuttis's "C Templates: The Complete Guide," which suggests writing inline when it is truly desired.
The above is the detailed content of Should You Use the `inline` Keyword with C Templates?. For more information, please follow other related articles on the PHP Chinese website!