A similar question of non-templated class
For a template class,
template <typename T>
struct Test {
T data;
static const Test constant;
};
it's fine when defining a static constexpr
member variable of specialized type:
template <>
inline constexpr Test<int> Test<int>::constant {42};
https://godbolt.org/z/o4c4YojMf
While results are diverged by compilers when defining a static constexpr
member directly from a template class without instantiation:
template <typename T>
inline constexpr Test<T> Test<T>::constant {42};
https://godbolt.org/z/M8jdx3WzM
GCC
compiles.
clang
ignores the constexpr
specifier in definition.
MSVC
... /std:c++17
works well, but /std:c++20
rejects due to redefinition.
I have learnt that constexpr
can be applied to the definition a variable or variable template
And in this example, which one is right? Why?