函数模板错误 -- 尚未声明

error with function template -- has not been declared

本文关键字:未声明 错误 函数模板      更新时间:2023-10-16

我正在做一些练习来理解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

简化的文件如下

------文件测试1.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

-----文件测试2.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;}
}

-----文件主.cpp -------

#include "test2.h"
#include "test1.h"
int main()
{}

你能帮我找出错误在哪里吗?

提前谢谢。

名称T是模板参数的标识符。它不存在于任何命名空间中。参数名称或局部变量也不能限定。只需删除my::即可。它似乎是一个剩余的 frim 一个使用my::myclass代码版本,这不是一个函数模板。

有了限定条件,您将引用命名空间范围内的名称:

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