2014-11-15 154 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; 
    } 
}