I was just in class, learning about STL and class templates. My teacher said you cannot split the class declaration and the function definitions into the normal header/cpp file like you can with non template classes.

Is this true, and if so why? I assume it would have somthing to do with the linking process because you can choose any datatype to work with in templates?

Thanks

Recommended Answers

All 4 Replies

I was just in class, learning about STL and class templates. My teacher said you cannot split the class declaration and the function definitions into the normal header/cpp file like you can with non template classes.

Is this true, and if so why? I assume it would have somthing to do with the linking process because you can choose any datatype to work with in templates?

Thanks

Yes for now its true. Although if your compiler supports the
keyword export, then you can separate the definition and the header file. Did you ask the teacher about this ? She
would have probably gave you a through answer.

For now? Are they fixing this currently?

Actually, it is only partially true. For many template classes you know that you are only going to have a few well known types to create. In that case you can use explicit template initialization. e.g.

//file  test.h
template<typename T>
class test
{
   T x;
public: 
   void addStuff(const T&);
   // ... 
};
// FILE: test.cpp
template<typename T>
void test<T>::addStuff(const T& A)
{
    x+=A;
} 
// THIS IS THE BIT TO create instances
template class test<double>;
template class test<std::complex<double> >;
template class test<int>;

So as you can see you can separate BUT you have to know what you are going to need. It is reasonably easy to do if you are the end user of the templates AND it speeds up compiles dramatically.

I have some (horrible) perl scripts that strips the error file from gcc to add the correct instances, but it isn't that difficult to do by hand or write something a million times better than my scripts.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.