Path: csiph.com!x330-a1.tempe.blueboxinc.net!newsfeed.hal-mli.net!feeder3.hal-mli.net!newsfeed.hal-mli.net!feeder1.hal-mli.net!news.stack.nl!aioe.org!.POSTED!not-for-mail From: "U.Mutlu" Newsgroups: comp.lang.c++ Subject: Re: moving template implementation to cpp Date: Sat, 04 Feb 2012 20:11:30 +0100 Organization: mutluit.com Lines: 107 Message-ID: <4F2D82E2.4090104@mutluit.com> References: <4f2cc7a0$0$10048$cc2e38e6@news.uslec.net> NNTP-Posting-Host: pRwUsNVUyKe9aWXvXIWyQA.user.speranza.aioe.org Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit X-Complaints-To: abuse@aioe.org User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:8.0.1) Gecko/20111121 Firefox/8.0.1 SeaMonkey/2.5 X-Notice: Filtered by postfilter v. 0.8.2 Disposition-Notification-To: "U.Mutlu" Xref: x330-a1.tempe.blueboxinc.net comp.lang.c++:13740 LR wrote, On 02/04/12 06:51: > U.Mutlu wrote: > >> Why must one place template code in header file? > > Maybe this will help. > > [35.12] Why can't I separate the definition of my templates class from > its declaration and put it inside a .cpp file? > > http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12 Thanks. I now found the following IMHO acceptable solution to the/my problem: //----- file: inc.hpp ------------------------------------------------ /* Moving template implementation out of header file. Hiding implementation details by moving it into the cpp file. The method below (see esp. file1.cpp) should be put into the C++ FAQ under 35.12 and 35.13. This method as shown here works for the defaulting typename, but one can add more types in a similar fashion as shown in file1.cpp. Author: U.Mutlu (www.mutluit.com) Build g++: g++ file1.cpp file2.cpp main.cpp Build MSC++: cl file1.cpp file2.cpp main.cpp */ struct TS1 { }; struct TS2 { }; // implementation in file1.cpp template class TC1 { public: TC1(); void f(); }; extern TC1<> gC1; // implementation in file2.cpp class TC2 { public: TC2(); void f(); // inside it makes call to gC1.f() (just for testing) }; //----- file: file1.cpp ---------------------------------------------- #include "inc.hpp" template TC1::TC1() { } template void TC1::f() { } // SOLUTION OF THE (LINK-) PROBLEM: specialize (instantiate) it // for the desired type (or types, by repeating it for each type): template<> TC1::TC1() { } template<> void TC1::f() { } //----- file: file2.cpp ---------------------------------------------- #include "inc.hpp" TC2::TC2() { } void TC2::f() { gC1.f(); } //----- file: main.cpp ----------------------------------------------- #include "inc.hpp" // test application: TC1<> gC1; int main(int argc, char* argv[]) { TC2 C2; C2.f(); return 0; }