Template函数不是命名空间的成员

Template function is not a member of a namespace

本文关键字:成员 命名空间 函数 Template      更新时间:2023-10-16

我有一个头文件RandFunctions.hpp,它包含一个模板函数

#ifndef _RANDFUNCTIONS_HPP_
#define _RANDFUNCTIONS_HPP_
#include <stdlib.h>
#include <time.h>
namespace surena
{
  namespace common
  {
template<typename RealT> inline
RealT
RealRandom()
{
  return rand()/(RealT(RAND_MAX)+1);
}  
  };
};
#endif

以及另一个头文件Search.hpp,其包括RandFunctions.hpp

#ifndef _SEARCH_HPP_
#define _SEARCH_HPP_
#include "RandFunctions.hpp"
#include <stdlib.h>
#include <time.h>
namespace surena
{
  namespace search
  {
template<typename RealT>
class CTest
{
  public:
    CTest() {srand((unsigned)(time(0)));}
    RealT
    GenRand(){ return common::RealRandom(); }
};
  };
};
#endif

当我在cpp文件中包括Search.hpp时,例如

#include "Search.hpp"
int
main(int argc, char** argv)
{
  CTest<float> test;
  return(0);
}

我得到以下编译时错误:

‘RealRandom’ is not a member of ‘surena::common’

这里怎么了?

由于RealRandom是一个没有参数的模板函数,因此需要提供一个模板参数:

GenRand(){ return common::RealRandom<RealT>(); }
                                    ^^^^^^^

此外,在main中,您必须使用适当的名称空间限定test变量:

surena::search::CTest<float> test;
^^^^^^^^^^^^^^^^