【问题标题】:Specialization of a function in different namespace不同命名空间中的函数的特化
【发布时间】:2018-03-23 07:01:09
【问题描述】:

我在尝试构建代码时收到以下错误。

src/Test.cxx:29:错误:'模板 T 的特化 com::check::one::Test::getValue(const std::string&)' 在不同的 命名空间 ./incl/Test.hxx:30:错误:来自定义 '模板 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
}

我使用了正确的命名空间并包含了头文件。编译没有问题。即使我在源文件中定义了测试类的其他成员函数。这些功能没有问题。只有具有模板的此功能存在问题。错误是在构建期间。谁能帮我解决这个问题?

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

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

    你也应该阅读Why can templates only be implemented in the header file。

    【讨论】:

    • 抱歉这里打错了。我在源代码中正确定义了它。
    【解决方案2】:

    我希望 cpp 文件中有这样的内容:

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

    这个:

    using namespace com.check.one;
    

    更像 Java 而不是 C++。 C++ - using namespace com::check::one;。它是用来使用命名空间的,而不是用来定义其中的东西。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-02
      • 1970-01-01
      • 2021-06-30
      • 1970-01-01
      • 2015-08-04
      • 2017-05-31
      • 2011-03-15
      • 1970-01-01
      相关资源
      最近更新 更多