2014-11-15 162 views
0

我正在做一些練習來理解C++模板。我的意圖是做一個功能模板,改變基於模板類的行爲。函數模板錯誤 - 尚未聲明

我獲得以下錯誤消息:

In file included from main.cpp:2:0: 
test1.h: In function ‘int my::fun(char*, int)’: 
test1.h:12:26: error: ‘my::T’ has not been declared 

簡化文件以下

------文件test1.h -------

#ifndef TEST_1_H 
#define TEST_1_H 

#include "test2.h" 

namespace my 
{ 
    template <typename T = myclass> 
    int fun(char* str,int dim) 
    { 
    return my::T::fun(str,dim); 
    } 
} 

#endif 

----- file test2.h -------

#ifndef TEST_2_H 
#define TEST_2_H 

namespace my 
{ 
    struct myclass 
    { 
    static int fun(char* str,int dim); 
    }; 
} 

#endif 

------文件測試2.cpp --------

#include "test2.h" 

namespace my 
{ 
    int myclass::fun(char* str,int dim) 
    {return 0;} 
} 

-----文件main.cpp中-------

#include "test2.h" 
#include "test1.h" 

int main() 
{} 

燦你請幫我弄清楚哪裏有錯誤?

在此先感謝。

+0

要編譯我用新的標準: G ++ -std = C++ 11測試2.cpp的main.cpp – GTA

+0

只是刪除了我的::之前T.模板參數不在命名空間中。 –

+0

Hi Coert, 它工作正常。 非常感謝。 因此,當我使用模板參數時,我永遠不能限定模板參數。 – GTA

回答

0

名稱T是模板參數的標識符。它不適用於任何名稱空間。參數名稱或局部變量也不能被限定。只要刪除my::。它似乎是一個使用my::myclass而不是函數模板的代碼版本。

隨着你指的是一個名字在命名空間範圍資格:

namespace my { 
    struct T {}; 
    template <typename T> 
    void f() { 
     my::T from_namespace; 
     T  from_template_argument; 
    } 
}