Initializing a static template member of a template class

I have the following piece of code, but it doesn't work. the dataMap member must contain a callback function that takes T & and T to jump to the callback at the appropriate time. Template member initialization fails (with g ++ 4.7.2) with: error: need ‘typename’ before ‘MyClass<T>::DataMap’ because ‘MyClass<T>’ is a dependent scope

. I tried to stick typename in the place where he says, but then received another error: error: expected primary-expression before ‘;’ token

. Can I do it like this, or do I need to remove the typedefs from initialization? I tried to go this route but it quickly became illegible and spat out even more errors.

template <typename T> class MyClass
{
public:
  typedef void(*CallbackType)(T&);
  typedef std::unordered_map<int, std::pair<T, CallbackType>/**/> DataMap;
  static DataMap dataMap;
  ...
};

template <typename T> MyClass<T>::DataMap MyClass<T>::dataMap = MyClass<T>::DataMap;

      

+3


source to share


1 answer


The compiler correctly prompts you to include the keyword typename

because it DataMap

is a dependent name in MyClass<T>::DataMap

. The definition of a static member should look like this:

template <typename T>
typename MyClass<T>::DataMap MyClass<T>::dataMap;

      



The element will be created by default, so there is no need to copy-initialize it . So it is enough to omit the part = MyClass<T>::DataMap

(which gives you problems because you forgot the parentheses after DataMap

on the right side of the copy initialization):

// This is also valid (mind the parentheses to invoke the
// constructor of `DataMap`), but unnecessary.
template <typename T>
typename MyClass<T>::DataMap MyClass<T>::dataMap = MyClass<T>::DataMap();

      

+7


source







All Articles