Are C++ variable templates inline?

Viewed 444

It has come to my notice that C++ Standard Library defines traits by means of variable templates, which are explicitly declared as inline:

      template <class T> inline constexpr bool is_void_v = is_void<T>::value;
      template <class T> inline constexpr bool is_null_pointer_v = is_null_pointer<T>::value;
      template <class T> inline constexpr bool is_integral_v = is_integral<T>::value;

I thought that all variable templates are inline by default. Is there any particular reason to declare them inline in this case?

2 Answers

Class members which are both static and constexpr are also implicitly inline. Non-members do not have this property. And variable templates are not implicitly inline.

Indeed, non-static, non-member template functions and variables have to be explicitly declared inline.

It is not true that templates are inline by default. The rules for default inlining suggest that when functions are defined within the class declaration, they should be considered for inlining. For templates, since most templates are defined inside the template class declaration, they are mostly inlined. However, it is possible to generate out-of-line templates:

template<typename T> class templateClass {
    public:
    void doSomething();
};

template<typename T> void templateClass<T>::doSomething() {
    //out of line implementation.
}
Related