Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.c++ > #13740

Re: moving template implementation to cpp

From "U.Mutlu" <for-usenet@mutluit.com>
Newsgroups comp.lang.c++
Subject Re: moving template implementation to cpp
Date 2012-02-04 20:11 +0100
Organization mutluit.com
Message-ID <4F2D82E2.4090104@mutluit.com> (permalink)
References <jgiftc$smk$1@speranza.aioe.org> <4f2cc7a0$0$10048$cc2e38e6@news.uslec.net>

Show all headers | View raw


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<typename T = TS1> 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<typename T> TC1<T>::TC1()
{
}

template<typename T> void TC1<T>::f()
{
}

// SOLUTION OF THE (LINK-) PROBLEM: specialize (instantiate) it
// for the desired type (or types, by repeating it for each type):
template<> TC1<TS1>::TC1()
{
}

template<> void TC1<TS1>::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;
}

Back to comp.lang.c++ | Previous | Next — Previous in thread | Find similar | Unroll thread


Thread

moving template implementation to cpp "U.Mutlu" <for-usenet@mutluit.com> - 2012-02-04 06:32 +0100
  Re: moving template implementation to cpp LR <lruss@superlink.net> - 2012-02-04 00:51 -0500
    Re: moving template implementation to cpp "U.Mutlu" <for-usenet@mutluit.com> - 2012-02-04 20:11 +0100

csiph-web