0

foo.h

template<typename T>
class stable_vector
{
    template<typename itor>
    stable_vector(itor, itor,
                  typename std::enable_if<!std::is_integral<itor>::value>::type* = nullptr)
    {
        // Implementation (T might be used)
    }
}

How can I split the implementation from header file and change the above to declaration?

Kevin Dong
  • 5,001
  • 9
  • 29
  • 62
  • possible duplicate of [Why can templates only be implemented in the header file?](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – Borgleader Jun 01 '15 at 17:29

2 Answers2

1

The definition of a template usually needs to be in the header so that the compiler can instantiate the template for every type T it is being used with.

In order to have the definition of your functions, it means you have to manually instantiate the template for every type T, otherwise, this will lead to linker errors that might be hard to solve.

Unless you know what you are doing, you should let your template definitions in the header file.

Dalzhim
  • 1,970
  • 1
  • 17
  • 34
0

You can't remove the implementation from the header. because a template implementation must be visible in the time of instantiation.

So you can either just move the implementation outside of the class below the class, or in a different header (if you want to have all the implementation in once file).

template<typename T>
class stable_vector
{
    template<typename itor>
    stable_vector(itor, itor,
                  typename std::enable_if<!std::is_integral<itor>::value>::type* = nullptr);

};

template <typenmae T> template<typename itor>
stable_vector<T>::stable_vector itor, itor,
                      typename std::enable_if<!std::is_integral<itor>::value>::type* = nullptr)
{

}

Or if you want to put it in a different file:

foo.h:

template<typename T>
class stable_vector
{
    template<typename itor>
    stable_vector(itor, itor,
                  typename std::enable_if<!std::is_integral<itor>::value>::type* = nullptr);

};

//include implementation file after decleration
#include fooImplementation.h

fooImplementation.h:

template <typenmae T> template<typename itor>
stable_vector<T>::stable_vector itor, itor,
                      typename std::enable_if<!std::is_integral<itor>::value>::type* = nullptr)
{

}
Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185