Search code examples
c++visual-studio-2010templates

Visual Studio not giving me errors because of template before each function. C++


Visual studio isn't giving me errors because of the template line before each function.

For example:

template <class keyType, class valueType>
void Map<keyType, valueType>::remove (keyType key)
{
cout<<"hello"
}

It won't give me an error for the missing semicolon on the cout.

How can i fix this? Thanks!


Solution

  • This is a well-known foible of the Visual C++ compiler. It boils down to this: Template bodies are not parsed unless and until the template is instantiated.

    When the compiler finds a template definition, it copies it into an internal buffer for future reference. Then, when that template is instantiated with concrete types, it does a search-and-replace to put the concrete types in and then parses the template.

    This has several nasty effects:

    • As you've noted, uninstantiated templates don't give error messages. This means you can write crap code, leave it in the code base and have no problem until, years down the line, someone foolishly instantiates your template and the build breaks in horrible ways.
    • Because the compiler knows the template parameters when it parses the template, the distinction between dependent and non-dependent names disappears.
    • Similarly, the parsing context for the template is the instantiation context, not the definition context. So, if you refer to a free function in your template, you'd better hope that function name doesn't have different definitions in different parts of your code...
    • Because the compiler knows the template parameters when it parses the template, there are many places where VC++ can tell the difference between a type name and an expression when the standard says it shouldn't and you should have to use the typename keyword to tell it the difference. Such code won't compile under any other compiler.

    Fair enough, once upon a time all compilers parsed templates this way. Everyone else has seen it for the maintainability and portability disaster that it is, but not Microsoft. Time to move on.