简体   繁体   English

C ++:初始化在头文件中声明的模板构造函数/例程?

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

I have a template defined in my header file as follows: 我在头文件中定义了一个模板,如下所示:

 template<typename T> class BoundedBuffer {
    unsigned int size;
    T entries[];
  public:
    BoundedBuffer( const unsigned int size = 10 );
    void insert( T elem );
    T remove();
};

However, when I try to initialize the constructor: 但是,当我尝试初始化构造函数时:

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

I get the following error (the first line of the previous code block is 17): 我收到以下错误(上一个代码块的第一行是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â

The right syntax is: 正确的语法是:

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

Note that optional parameters should not be declared in functions definitions but ony in functions declarations. 注意,可选参数不应在函数定义中声明,而应在函数声明中声明。

class aaa
{
    // declaration
    void xxx(int w = 10);
};

// definition
void aaa::xxx(int w)
{
    ...
}

Note that everything for templated class should stay in H files. 请注意,模板化类的所有内容都应保留在H文件中。

"They must be in the same translation unit. It is quite common in some libraries to separate the template implementation into a .tpp (or some other extension) file that is then included in the .h where the template is declared." “它们必须位于同一翻译单元中。在某些库中,将模板实现分离为.tpp(或其他扩展名)文件,然后将其包含在声明模板的.h中是很常见的。” as Michael Price said. 正如迈克尔·普莱斯(Michael Price)所说。

Templates are not normal types and they cannot be linked. 模板不是普通类型,因此无法链接。 They are instantiated only when requested. 仅在请求时实例化它们。

Note that constructors fields initializers need the ":" character. 请注意,构造函数字段初始化器需要使用“:”字符。

class MyClass
{
public:
    int x;

    MyClass() : x(10) { /* note that i used : character */ }
};

您必须在标头中实现模板的所有方法,因为模板的用户需要能够看到那些方法以将其实例化为给定类型。

Your declaration should be: 您的声明应为:

template< typename T >
BoundedBuffer<T>::BoundedBuffer( const unsigned int size ) : size( size ) {...}

Note that it also has to be in the header file, as mentioned by @Dean Povey. 请注意,它也必须位于标头文件中,如@Dean Povey所述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM