I'm trying to use a static member in a normal member function. But the compiler report some errors. Pls take a look at this code
#include <memory>
template<typename T>
class MyClass {
private:
static std::allocator<T> alloc;
T *p;
public:
void assign(T e) {
p = alloc.allocate(1);
alloc.construct(p, e);
}
};
and this is how I use it:
#include 'myclass.h'
int main() {
MyClass<int> cls;
cls.assign(4);
};
And the compiler give this error:
/Users/liuziqi/CLionProjects/cpplearning/src/tt.h:17:9: warning: instantiation of variable 'MyClass<int>::alloc' required here, but no definition is available [-Wundefined-var-template]
p = alloc.allocate(1);
^
/Users/liuziqi/CLionProjects/cpplearning/src/main.cpp:49:7: note: in instantiation of member function 'MyClass<int>::assign' requested here
cls.assign(4);
^
/Users/liuziqi/CLionProjects/cpplearning/src/tt.h:13:28: note: forward declaration of template entity is here
static std::allocator<T> alloc;
^
/Users/liuziqi/CLionProjects/cpplearning/src/tt.h:17:9: note: add an explicit instantiation declaration to suppress this warning if 'MyClass<int>::alloc' is explicitly instantiated in another translation unit
p = alloc.allocate(1);
I can not figure out which part is wrong.....I have defined that static member and any member function should be able to use it. Is this error relevant to template? (I've just learned template and not sure If I use it correctly.)