如何从头文件中分离模板构造函数
How can I split the template constructor from the header 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)
{
// 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)
{
}
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- 构造函数正在调用一个使用当前类类型的函数
- 没有用于初始化C++中的变量模板的匹配构造函数
- 初始化具有非默认构造函数的std::数组项的更好方法
- 当从函数参数中的临时值调用复制构造函数时
- 在c++构造函数中使用随机字符串生成器
- 一对向量构造函数:初始值设定项列表与显式构造
- 从构造函数抛出异常时如何克服内存泄漏
- 如何将显式声明的构造函数分离到 .h 和 .cpp 文件中?
- 如何分离模板构造函数的实现(如果类不是模板)
- C++分离了对象的定义和构造函数
- 如果模板类构造函数和成员函数的定义与使用分离,则G++链接器找不到它们
- Singleton构造函数与get_instance()分离
- 如何从头文件中分离模板构造函数