Do templates maintain separation?

57 views
Skip to first unread message

Clayton Weaver

unread,
Jan 12, 2017, 8:27:45 PM1/12/17
to ISO C++ Standard - Discussion
By separation, I simply mean declaration/definition (.h/.cpp). Every book I know of stresses separating the definition from the declaration. Upon learning templates I read that they force you to include everything in the header file:

template<typename T>
class Vec{
         T val;
    public:
        T funct() const { return val; }
};

Then I found a site where a person did this:

// collection.h
template<typename T>
class Collection{
     public:     
          bool isempty() const;
};

// collection.cpp
template<typename T>
bool Collection<T>::isempty()const
{
     //....
}

//main.cpp
Collection<int> col1;
Collection<string> col2; // etc.

Due to that site I'm confused. Do templates allow to maintain declaration/definition separation or not? 

Sincerely,
Clayton Weaver

Thiago Macieira

unread,
Jan 12, 2017, 9:15:00 PM1/12/17
to std-dis...@isocpp.org
On quinta-feira, 12 de janeiro de 2017 17:27:45 PST Clayton Weaver wrote:
> Due to that site I'm confused. Do templates allow to maintain
> declaration/definition separation or not?

Yes, but there's a caveat:

In the header, you need to declare which instantiations will appear in the
.cpp file.

In the .cpp, you need to instantiate them.

And you cannot use any instantiation that isn't in the .cpp.

--
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
Software Architect - Intel Open Source Technology Center

Clayton Weaver

unread,
Jan 13, 2017, 3:30:52 AM1/13/17
to ISO C++ Standard - Discussion
Thank you for clearing that up for me.
Reply all
Reply to author
Forward
0 new messages