C++ static member of class template — linker warning “multiple definition” [duplicate]

懵懂的女人 提交于 2020-01-23 13:21:11

问题


Let's say for some reason, I want to have a class template MyTemp with some static data member smDummyVar :

Mytemp.h

#ifndef MY_TEMP_H
#define MY_TEMP_H

template<class T>
class MyTemp{
...
private:
   static int smDummyVar;
   ...
};

#include "MyTemp.cpp"

#endif //MY_TEMP_H

Mytemp.cpp

...
template<class T> int MyTemp<T>::smDummyVar = 0;
...

Since the compiler requires that the definition and declaration of a template be at the same place, so I include MyTemp.cpp in MyTemp.h .

Now: I want to use MyTemp at many places and create objects using the template:

case1.cpp

#include "MyTemp.h"

void dummyfunc1(){
    MyTemp<int> myTemp1;
}

case2.cpp

#include "MyTemp.h"

void dummyfunc2(){
    MyTemp<int> myTemp2;
}

I won't get any error from the compiler, but I'd get warning from the linker:

"multiple definition for MyTemp<int>::smDummyVar" ... defined in invalid_group(case1.o) ... rejected in favour of symbol defined in ...(case2.o)

Question: how can I get rid of this warning ?

Thanks a lot in advance for your help !

====================================

inspired by one of the answers in this thread Why can templates only be implemented in the header file? I found the following solution:

i. remove #include "MyTemp.cpp" in MyTemp.h

ii. specialized.h

#include "MyTemp.h"
typedef MyTemp<int> MySpecialized;

iii. specialized.cpp

#include "MyTemp.cpp"
template class MyTemp<int>;

iv. give specialized.cpp to cmake file

v. include specilized.h in case1.cpp and case2.cpp

the "multiple definition" warning issued by the linker will go away.

Thank you guys for helping !

来源:https://stackoverflow.com/questions/51408276/c-static-member-of-class-template-linker-warning-multiple-definition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!