Search code examples
c++templatesvisual-studio-2013final

Why is this code allowed to compile under Visual Studio 2013?


Here is a very simple C++11 program that tests out the use of the final keyword to prevent a class from being subclassed:

template<class T> class Base final
{
public:
   Base() {}

private:
   T t;
};

class Derived : public Base<int> {};

int main(int, char **)
{
   Derived d;
   return 0;
}

If I try to compile the above program under Mac OS X (Clang), I get the expected error messages:

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

However, if I compile the same code under Windows using Visual Studio 2013, it compiles with no errors. If I make the Base class non-templated, however, Visual Studio does recognize the final keyword and emits an error.

Is this a bug in Visual Studio 2013, or am I missing some nuance about how the final keyword is allowed/expected to operate in conjunction with templated classes?


Solution

  • It is indeed a 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.