初始化头文件中声明的模板构造函数/例程

C++: initializing template constructor/routine declared in header file?

本文关键字:构造函数 例程 文件 声明 初始化      更新时间:2023-10-16

在头文件中定义了一个模板,如下所示:

 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所提到的。