Why do templated class data members require the static keyword?

Viewed 90

What is the rationale that this does not compile?

class Math{
   template<typename T>
   std::map<int, T> m;   // error: member 'm' declared as a template
};

while making the data member static compiles?

class Math{
   template<typename T>
   static std::map<int, T> m;
};
1 Answers

This answer was posted by Peter (under the CC BY-SA 4.0 license), as a comment to the question Why do templated class data members require the static keyword?.


For exactly the reason the diagnostic described. A non-static data member of a class cannot be a template, since it means that each instance of the class has an unbounded (potentially infinite) number of members named m - which would all need to be stored in an instance of the class simultaneously. That makes the size of the containing class indeterminate. A static member can be a template, since each instantiation can be referred to unambiguously and need not all be stored simultaneously in a single object. It's not a case of static being needed - one case is achievable and one is not

Related