locked
Coding error in templated method switch statement overlooked by compiler RRS feed

  • Question

  • Does anybody know why this compiles without an error? The linux/GCC compiler complains as it should.

    template <class T> void switchTest()
    {
      enum EnumType {A, B};
      EnumType enum_var = A;
    
      switch (enum_var) {
      case A:
       break;
      case B:
       break;
      case DOESNT_EXIST: // Should generate a compile error
       break;
      }
    }
    
    I'm Running Visual Studio 2010 10.0.30319.1 RTMRel.
    
    Friday, January 21, 2011 6:24 PM

Answers

  • On 1/21/2011 1:24 PM, CodeCosmonaut wrote:

    Does anybody know why this compiles without an error? The linux/GCC compiler complains as it should.


    template<class T> void switchTest() { enum EnumType {A, B}; EnumType enum_var = A; switch (enum_var) { case A: break; case B: break; case DOESNT_EXIST: // Should generate a compile error break; } } I'm Running Visual Studio 2010 10.0.30319.1 RTMRel.

    MSVC only does minimal parsing when compiling bodies of function templates - basically just enough to find the closing brace. If I recall correctly, this would compile too:

    template <typename T> void f() { blah blah blah }

    It then parses again, for real, when the function is instantiated. If you try to actually call switchTest, you'll get a compiler error at that point.


    Igor Tandetnik

    • Marked as answer by CodeCosmonaut Friday, January 21, 2011 9:13 PM
    Friday, January 21, 2011 6:33 PM

All replies

  • On 1/21/2011 1:24 PM, CodeCosmonaut wrote:

    Does anybody know why this compiles without an error? The linux/GCC compiler complains as it should.


    template<class T> void switchTest() { enum EnumType {A, B}; EnumType enum_var = A; switch (enum_var) { case A: break; case B: break; case DOESNT_EXIST: // Should generate a compile error break; } } I'm Running Visual Studio 2010 10.0.30319.1 RTMRel.

    MSVC only does minimal parsing when compiling bodies of function templates - basically just enough to find the closing brace. If I recall correctly, this would compile too:

    template <typename T> void f() { blah blah blah }

    It then parses again, for real, when the function is instantiated. If you try to actually call switchTest, you'll get a compiler error at that point.


    Igor Tandetnik

    • Marked as answer by CodeCosmonaut Friday, January 21, 2011 9:13 PM
    Friday, January 21, 2011 6:33 PM
  • On 21/01/2011 19:33, Igor Tandetnik [MVP] wrote:

    MSVC only does minimal parsing when compiling bodies of function templates - basically just enough to find the closing brace. If I recall correctly, this would compile too:

    template<typename T>  void f() { blah blah blah }

    It does compile with VC10.

    Giovanni

    Friday, January 21, 2011 10:53 PM