2010-07-13 68 views
1

我正在嘗試製作一個模板對象成員在其中的類。例如如何在類中包含模板成員?

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

當我做到這一點,我收到的錯誤結果是:

make

g++ -m32 -fPIC -Werror -Wall -Wunused-function -Wunused-parameter -Wunused-variable -I. -I/views/EVENT_ENGINE/LU_7.0-2/server/CommonLib/include -I/views/EVENT_ENGINE/LU_7.0-2/server/Common/Build/Include -g -c -o ${OBJ_DIR}/testTemp.o testTemp.cxx

testTemp.cxx:48: error: expected identifier before string constant

testTemp.cxx:48: error: expected ',' or '...' before string constant

testTemp.cxx:50: error: 'test2' is not a type

make: *** [/views/EVENT_ENGINE/LU_7.0-2/server/applications/event_engine/Obj/testTemp.o] Error 1

我在做什麼錯?如果我們希望模板類型始終與特定類相同,如何在模塊中「嵌入」模板?

在此先感謝您的幫助。

回答

2

這與模板無關 - 您無法直接在類定義中初始化非靜態成員(C++ 03,§9.2/ 4):

A member-declarator can contain a constant-initializer only if it declares a static member (9.4) of const integral or const enumeration type, see 9.4.2.

如果你想明確地初始化數據成員,使用構造函數初始化列表:

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

爾加!我正在尋找斑馬,專注於模糊的錯誤信息,並認爲它必須是模板中特別的東西。我完全忽略了嵌套類的基礎知識。 感謝所有的評論。我不會再犯這個錯誤了。 – 2010-07-13 22:57:19

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) 
    { 

    } 
}; 
0

化妝默認的構造函數爲您blah類。 並在構造函數初始化列表中初始化模板對象的值

相關問題