Can the specification of a member function of a template also be an instance?

I ran into the problem of template specialization. The following builds and runs, but I'm not sure what this should:

// template.h template <typename T> class interface{ public: void doSomething(); }; // template.cpp #include "template.h" #include <iostream> template <> void interface<int>::doSomething(){std::cout << "Did something\n";} // main.cpp #include "template.h" int main(){ interface<int> instance; instance.doSomething(); return 0; }; g++ main.cpp template.cpp; ./a.out 

My understanding was that all compilation units should have access to all specialized templates that are not in main.cpp. If I understand what is going on correctly, specialization in template.cpp also creates an <int> interface, so the symbol is generated and everything connects happily. However, I am sure that this falls into the realm of uncertainty, and I cannot count on the fact that it always works everywhere. Can anyone confirm or refute my suspicions?

Thanks!

+6
source share

All Articles