简体   繁体   English

由于命名空间,c++ 无法解释的类“尚未声明”错误

[英]c++ Unexplainable class “ has not been declared” error due to namespace

I have some template class that has two private static members.我有一些模板类,它有两个私有静态成员。 Users define a traits struct and provide it to the template class, which then derives from it.用户定义一个 traits 结构并将其提供给模板类,然后模板类从它派生。

Then in a c++ file the user define the static members, with one member initialized from the other.然后在 C++ 文件中,用户定义静态成员,其中一个成员从另一个初始化。 For some reason I get a "class has not been declared" error if I dont fully specify the namespace for the arg.出于某种原因,如果我没有完全指定 arg 的命名空间,我会收到“类尚未声明”错误。 This is only an issue when I'm in a nested namespace, there is no issue if you define the type in a single top level namespace, which makes me think this is a compiler bug.这只是当我在嵌套命名空间中时的问题,如果您在单个顶级命名空间中定义类型就没有问题,这让我认为这是一个编译器错误。 Trimmed down example below, compiling with gcc 7.2修剪下面的例子,用gcc 7.2编译

template<typename Traits>
struct Base 
{
    static int x;
    static int y;
};

namespace foo::bar
{
    struct BarTraits
    {
    };

    using Bar = Base<BarTraits>;

    template<> int Bar::x = 0;
    template<> int Bar::y( Bar::x );  //error 
    //template<> int Bar::y( foo::bar::Bar::x ); //no error
}

According to C++ standard temp.expl.spec#3根据 C++ 标准temp.expl.spec#3

An explicit specialization may be declared in any scope in which the corresponding primary template may be defined.可以在可以定义相应主模板的任何范围内声明显式特化。

Your code violates this statement, because Bar::x and Bar::y are specialized in namespace foo::bar .您的代码违反了此声明,因为Bar::xBar::y专门用于namespace foo::bar

GCC incorrectly accepts first two specializations because of known defect https://gcc.gnu.org/bugzilla/show_bug.cgi?id=56119由于已知缺陷,GCC 错误地接受了前两个专业化https://gcc.gnu.org/bugzilla/show_bug.cgi?id=56119

The following fixed code以下固定代码

template<typename Traits>
struct Base  {
    static int x;
    static int y;
};

struct BarTraits {};
using Bar = Base<BarTraits>;

template<> int Bar::x = 0;
template<> int Bar::y( Bar::x );

is accepted by GCC, Clang, MSVC: https://gcc.godbolt.org/z/MPxjTzbah被 GCC、Clang、MSVC 接受: https : //gcc.godbolt.org/z/MPxjTzbah

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM