如何从头文件中分离模板构造函数

How can I split the template constructor from the header file?

本文关键字:分离 构造函数 文件      更新时间:2023-10-16

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)
    }
}

如何将实现从头文件中分离出来,并将上面的内容更改为声明?

模板的定义通常需要在头中,这样编译器就可以为使用的每种类型T实例化模板。

为了定义你的函数,这意味着你必须手动实例化每个类型T的模板,否则,这将导致链接器错误,可能很难解决。

除非您知道自己在做什么,否则应该将模板定义放在头文件中。

您不能从标头中删除实现。因为模板实现在实例化时必须是可见的。

因此,您可以将实现移到类下面的类之外,也可以移到不同的头中(如果您希望将所有实现都放在一个文件中(。

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)
{
}

或者,如果你想把它放在另一个文件中:

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)
{
}