为什么允许此代码在 Visual Studio 2013 下编译?
Why is this code allowed to compile under Visual Studio 2013?
这是一个非常简单的 C++11 程序,它测试了使用 final
关键字来防止 class 被子class编辑:
template<class T> class Base final
{
public:
Base() {}
private:
T t;
};
class Derived : public Base<int> {};
int main(int, char **)
{
Derived d;
return 0;
}
如果我尝试在 Mac OS X (Clang) 下编译上述程序,我会收到预期的错误消息:
jeremy-friesners-mac-pro-3:~ jaf$ g++ -std=c++11 ./temp.cpp
./temp.cpp:10:28: error: base 'Base' is marked 'final'
class Derived : public Base<int> {};
^
./temp.cpp:1:29: note: 'Base' declared here
template<class T> class Base final
但是,如果我使用 Visual Studio 2013 在 Windows 下编译相同的代码,它编译时没有错误。但是,如果我使 Base
class 成为非模板,Visual Studio 会识别 final
关键字并发出错误。
这是 Visual Studio 2013 中的错误,还是我遗漏了关于 final
关键字如何 allowed/expected 与模板化 classes 结合使用的一些细微差别?
我不知道组合的所有内部结构,但恕我直言,这两个编译器都是 "correct"。 MSVC 看到模板 class 是最终的,您不能从中派生。您使用模板 class 来定义 class Base,它不再是最终的。
恕我直言,编译器的不同解释。
我认为这是 VS 2013 中的错误。
对于它的价值,来自 VS 2015 CTP 的编译器做了(我认为)您可能期望的事情:
test.cpp(10): error C3246: 'Derived': cannot inherit from 'Base<int>' as it has been declared as 'final'
确实是bug
N4296, [class]/p3:
If a class is marked with the class-virt-specifier final
and it appears as a base-type-specifier in a base-clause (Clause 10), the program is ill-formed.
这是一个非常简单的 C++11 程序,它测试了使用 final
关键字来防止 class 被子class编辑:
template<class T> class Base final
{
public:
Base() {}
private:
T t;
};
class Derived : public Base<int> {};
int main(int, char **)
{
Derived d;
return 0;
}
如果我尝试在 Mac OS X (Clang) 下编译上述程序,我会收到预期的错误消息:
jeremy-friesners-mac-pro-3:~ jaf$ g++ -std=c++11 ./temp.cpp
./temp.cpp:10:28: error: base 'Base' is marked 'final'
class Derived : public Base<int> {};
^
./temp.cpp:1:29: note: 'Base' declared here
template<class T> class Base final
但是,如果我使用 Visual Studio 2013 在 Windows 下编译相同的代码,它编译时没有错误。但是,如果我使 Base
class 成为非模板,Visual Studio 会识别 final
关键字并发出错误。
这是 Visual Studio 2013 中的错误,还是我遗漏了关于 final
关键字如何 allowed/expected 与模板化 classes 结合使用的一些细微差别?
我不知道组合的所有内部结构,但恕我直言,这两个编译器都是 "correct"。 MSVC 看到模板 class 是最终的,您不能从中派生。您使用模板 class 来定义 class Base
恕我直言,编译器的不同解释。
我认为这是 VS 2013 中的错误。
对于它的价值,来自 VS 2015 CTP 的编译器做了(我认为)您可能期望的事情:
test.cpp(10): error C3246: 'Derived': cannot inherit from 'Base<int>' as it has been declared as 'final'
确实是bug
N4296, [class]/p3:
If a class is marked with the class-virt-specifier
final
and it appears as a base-type-specifier in a base-clause (Clause 10), the program is ill-formed.