I have a specialization template class defined in another file. Therefore, you can create two versions of the same class: once, replacing the template parameter and once using specialization. My real understanding is that this can lead to two instances of the same type having different sizes in memory, which will lead to segmentation errors.
I created a minimal example, and the following code should illustrate the question:
Create a template class:
// - templateexample.h --------------- #ifndef TEMPLATEEXAMPLE_H #define TEMPLATEEXAMPLE_H template<typename T> class Example { public: Example(){} int doWork() {return 42;} }; #endif // -----------------------------------
Template specialization in another file:
// - templatespecialization.h -------- #ifndef TEMPLATESPECIALIZATION_H #define TEMPLATESPECIALIZATION_H #include "templateexample.h" template<> class Example<int> { public: Example() : a(0), b(1), c(2), d(3) {} int doWork() {return a+b+c+d;} private: int a; //<== the specialized object will be larger in memory int b; int c; int d; }; #endif // --------------------------------
Have a class that includes only the template class definition, but should include specialization.
// - ah -------------------------- #ifndef A_H #define A_H #include "templateexample.h" class A { public: Example<int> returnSmallExample(); }; #endif // - a.cpp ------------------------ #include "ah" Example<int> A::returnSmallExample() {return Example<int>();} // --------------------------------
The main class now knows two versions of Example<int> of that of A and one of templatespecialization.h.
// - main.cpp --------------------- #include <iostream> #include "ah" #include "templatespecialization.h" int main() { A a; Example<int> test = a.returnSmallExample(); std::cout<<test.doWork()<<std::endl; } // --------------------------------
Please note that this problem only occurs when class A is compiled separately, this example is from ideone 6 outputs, while using separate files can lead to segmentation phages or output 42 ( https://ideone.com/3RTzlC ). On my machine, the example compiles successfully and outputs 2013265920:

In the production version of the above example, everything is built into the shared library, which is used mainly.
Question 1: Why does the linker not detect this problem? This should be easy to detect by comparing the size of objects.
Question 2: is there a way to check object files or a shared library to detect multiple implementations of the same type as in the above example?
Edit: note: the above code is a minimal example to explain the problem. The reason for the situation is that the template class is from one library, and I cannot edit files from this library. Finally, all this is used throughout the executable, and now I need to find out if the problem occurs above.
Edit: The code above can be compiled as follows:
#!/bin/bash g++ -g -c a.cpp g++ -g -c main.cpp g++ -o test ao main.o