1
votes

I am getting the following error when I try to build the code.

src/Test.cxx:29: error: specialization of 'template T com::check::one::Test::getValue(const std::string&)' in different namespace ./incl/Test.hxx:30: error: from definition of 'template T com::check::one::Test::getValue(const std::string&)' src/Test.cxx:31: confused by earlier errors, bailing out

Header file:

namespace com::check::one
{
    class Test
    {
    public:
        template<typename T>
        T getValue(const std::string& var);
    };
}

Source File:

using namespace com::check::one;

template<>
std::vector<std::string> Test::getValue(const std::string& var)
{
    //statements
}

I am using the correct namespace and included the header file as well. No issues in compile. Even I have defined other member functions of the Test Class in source file. No issues for those functions. Only there is a issue with this function which has template. The error is during build. Can anyone help me to resolve this issue?

2

2 Answers

3
votes

using namespace com.check.one; is not a valid syntax. It should be:

using namespace com::check::one;

Even better, wrap definitions into namespace:

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
    }
}

Also you should read Why can templates only be implemented in the header file.

1
votes

I expect something like this in the cpp file:

namespace com {
namespace check {
namespace one {
template<>
std::vector<std::string> Test::getValue(const std::string& var)
{
//statements
}
}
}
}

This:

using namespace com.check.one;

is more like Java than C++. C++ - using namespace com::check::one;. And it's for using the namespace, not for defining things in it.