初始化头文件中声明的模板构造函数/例程
C++: initializing template constructor/routine declared in header file?
在头文件中定义了一个模板,如下所示:
template<typename T> class BoundedBuffer {
unsigned int size;
T entries[];
public:
BoundedBuffer( const unsigned int size = 10 );
void insert( T elem );
T remove();
};
但是,当我尝试初始化构造函数时:
BoundedBuffer<T>::BoundedBuffer( const unsigned int size = 10 ) size(size) {
// create array of entries
entries = new T[size];
// initialize all entries to null
for(int i = 0; i < size; i++)
entries[i] = null;
}
我得到以下错误(前一个代码块的第一行是17):
q1buffer.cc:17: error: âTâ was not declared in this scope
q1buffer.cc:17: error: template argument 1 is invalid
q1buffer.cc:17: error: expected initializer before âsizeâ
正确的语法是:
template <typename T>
BoundedBuffer<T>::BoundedBuffer(const unsigned int size) : size(size) {
// create array of entries
entries = new T[size];
// initialize all entries to null
for(int i = 0; i < size; i++)
entries[i] = null;
}
注意,可选形参不能在函数定义中声明,只能在函数声明中声明。
class aaa
{
// declaration
void xxx(int w = 10);
};
// definition
void aaa::xxx(int w)
{
...
}
请注意,模板化类的所有内容都应该留在H文件中。
"它们必须在同一个翻译单元中。在一些库中,将模板实现分离到。tpp(或其他扩展名)文件中是很常见的,然后将该文件包含在声明模板的。h文件中。
模板不是普通类型,它们不能被链接。它们只在被请求时被实例化。
注意,构造函数字段初始化式需要":"字符。
class MyClass
{
public:
int x;
MyClass() : x(10) { /* note that i used : character */ }
};
您必须在头文件中实现模板的所有方法,因为模板的用户需要能够看到这些方法来为给定的类型实例化它。
你的声明应该是:
template< typename T >
BoundedBuffer<T>::BoundedBuffer( const unsigned int size ) : size( size ) {...}
请注意,它也必须在头文件中,正如@Dean Povey所提到的。
相关文章:
- 具有非默认构造函数的单例类
- 在派生自线程类的构造函数中传递字符串
- 线程构造函数周围的可变参数模板包装器无法编译
- C++使用函数对象的线程,如何调用多个析构函数而不是构造函数?
- 运行 std::线程不在构造函数中
- 具有unique_ptr和线程的默认矢量构造函数
- 为什么当我在构造函数中创建线程时,实例化对象和对象的指针的行为不同
- 类成员在构造函数(线程)之后更改地址
- unordered_map中的C 线程(无复制构造函数)
- C 从类的构造函数运行Boost线程
- 通过类构造函数创建线程
- C++ 我的函数在我的 Image 类中工作,但不在主例程中工作
- 具有局部静态变量的单例构造函数
- 继承的模板化单例类 c++ 中未定义的构造函数
- 可以在构造函数初始值设定项列表中使用标准::线程
- 将类对象指针传递给默认构造函数(C 子例程)
- 构造函数在不同线程中的静态单例类上调用两次
- c++将各种参数传递给父类构造函数(线程c++11)
- 初始化头文件中声明的模板构造函数/例程
- 使用类构造函数在线程中启动成员函数