当我尝试构建代码时,我收到以下错误。
src/Test.cxx:29:错误:"模板 T "的专业化 com::check::one::test::getValue(const std::string&(' in different 命名空间 ./incl/Test.hxx:30:错误:来自 'template T com::check::one::Test::getValue(const std::string&(' src/Test.cxx:31:被早期的错误所迷惑,保释 外
头文件:
namespace com::check::one
{
class Test
{
public:
template<typename T>
T getValue(const std::string& var);
};
}
源文件:
using namespace com::check::one;
template<>
std::vector<std::string> Test::getValue(const std::string& var)
{
//statements
}
我正在使用正确的命名空间,并且还包含头文件。编译中没有问题。甚至我已经在源文件中定义了测试类的其他成员函数。这些功能没有问题。只有这个有模板的函数有问题。错误发生在生成过程中。谁能帮我解决这个问题?
using namespace com.check.one;
不是有效的语法。它应该是:
using namespace com::check::one;
更好的是,将定义包装到命名空间中:
namespace com::check::one
{
class Test
{
public:
template<typename T>
T getValue(const std::string& var);
};
}
namespace com::check::one
{
template<>
std::vector<std::string> Test::getValue(const std::string& var)
{
//statements
}
}
此外,您应该阅读为什么只能在头文件中实现模板。
我希望在 cpp 文件中出现这样的东西:
namespace com {
namespace check {
namespace one {
template<>
std::vector<std::string> Test::getValue(const std::string& var)
{
//statements
}
}
}
}
这:
using namespace com.check.one;
比起C++,更像Java。C++ - using namespace com::check::one;
.它用于使用命名空间,而不是用于定义其中的内容。