如何在类中包含模板成员?

时间:2010-07-13 00:56:17

标签: c++ templates

我正在尝试创建一个在其中包含模板对象成员的类。例如

mt_queue_c<int>    m_serial_q("string");

然而,当我这样做时,它无法编译。如果我在类定义的外部移动它以使它成为一个全局对象,它编译得很好。

我将代码压缩到最小的可能失败单元中,如下所示(是的,它没有意义,因为缺少其他成员变量和函数......)

#include <deque>
#include <queue>
#include <pthread.h>
#include <string>
#include <iostream>

template <class T, class Container = std::deque<T> >
class mt_queue_c {
public:
    explicit mt_queue_c(const std::string    &name,
                        const Container      &cont = Container()) :
        m_name(name),
        m_c(cont)
        {};
    virtual ~mt_queue_c(void) {};
protected:
    // Name of queue, used in error messages.
    std::string        m_name;

    // The container that manages the queue.
    Container          m_c;
};

// string object for a test
std::string  test2("foobar");

// Two tests showing it works as a global
mt_queue_c<char>   outside1("string");
mt_queue_c<char>   outside2(test2);

// Two failed attempts to include the object as a member object.
class blah {
    mt_queue_c<int>    m_serial_q("string");    // this is 48
    mt_queue_c<char>   m_serial_q2(test2);      // this is 50
};

// Adding main just because.
int main ()
{
    std::cout << "Hello World" << std::endl;
}

当我这样做时,我收到的错误结果是:

  

     

g ++ -m32 -fPIC -Werror -Wall   -Wunused-function -Wunused-parameter -Wunused-variable -I。 -I /视图/ EVENT_ENGINE / LU_7.0-2 /服务器/ CommonLib /包括   -I /视图/ EVENT_ENGINE / LU_7.0-2 /服务器/通用/建设/包括   -g -c -o $ {OBJ_DIR} /testTemp.o testTemp.cxx

     

testTemp.cxx:48:错误:字符串常量之前的预期标识符

     

testTemp.cxx:48:错误:在字符串常量之前预期','或'...'

     

testTemp.cxx:50:错误:'test2'不是类型

     

制作:***   [/views/EVENT_ENGINE/LU_7.0-2/server/applications/event_engine/Obj/testTemp.o]   错误1

我做错了什么?如果我们希望模板类型对于特定类始终相同,那么如何在类中“嵌入”模板?

提前感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

试试这个:

class blah { 
    mt_queue_c<int>    m_serial_q;    // this is 48 

    mt_queue_c<char>   m_serial_q2;      // this is 50 

    blah() : m_serial_q("string"), m_serial_q2(test2)
    {

    }
}; 

答案 1 :(得分:2)

这与模板无关 - 您无法直接在类定义中初始化非静态成员(C ++ 03,§9.2/ 4 ):

  

成员声明符只有在声明static成员(9.4)const整数或const枚举类型时才能包含常量初始值设定项,见9.4.2。

如果要显式初始化数据成员,请使用构造函数initializer-list:

blah::blah() : m_serial_q("string") {}

答案 2 :(得分:0)

为您的班级blah制作默认构造函数。 并在构造函数初始化列表中初始化模板对象的值

相关问题