user4442671
user4442671

Reputation:

Are static member variables of templates defined or specialized?

This relates to the following question: constexpr differences between GCC and clang

In the following spinet, is the last line a specialization, a definition, or both?

template<typename T>
struct A {
  static const T s;
};

template<typename T>
const T A<T>::s = T(1);

This seems like a definition to me, but the posted question being compiled successfully by gcc has me questioning my assumptions.

Upvotes: 0

Views: 42

Answers (1)

R Sahu
R Sahu

Reputation: 206737

It's definition.

The following would be a specialization.

template <>
const int A<int>::s = 20;

Given the following program,

#include <iostream>

template<typename T>
struct A {
  static const T s;
};

template <typename T>
const T A<T>::s = T(1);

template <>
const int A<int>::s = 20;

int main()
{
   double a = A<double>::s;
   double b = A<int>::s;

   std::cout << "a: " << a << std::endl;
   std::cout << "b: " << b << std::endl;
}

You should expect the output to be:

a: 1
b: 20

See it working at https://ideone.com/t7Hxk9

Upvotes: 1

Related Questions