5

Today one of my friends told me that the following code compiles well on his Visual Studio 2008:

#include <vector>
struct A
{
  static int const const_iterator = 100;
};
int i;
template <typename T>
void PrintAll(const T & obj)
{
  T::const_iterator *i;
}
int main()
{
  std::vector<int> v;
  A a;
  PrintAll(a);
  PrintAll(v);
  return 0;
}

I usually use g++, and it always refuse to pass the second PrintAll() call. As I know, for this problem, g++ is doing the standard way translating a template.

So, is my knowledge wrong, or is it a extension of VS2008?

hpsMouse
  • 2,004
  • 15
  • 20

2 Answers2

8

This is not an extension at all.

VC++ never implemented the two phases interpretation properly:

  1. At the point of definition, parse the template and determine all non-dependent names
  2. At the point of instantiation, check that the template produces valid code

VC++ never implemented the first phase... it's inconvenient since it means not only that it accepts code that is non-compliant but also that it produces an altogether different code in some situations.

void foo(int) { std::cout << "int" << std::endl; }

template <class T> void tfoo() { foo(2.0); }

void foo(double) { std::cout << "double" << std::endl; }

int main(int argc, char* argv[])
{
  tfoo<Dummy>();
}

With this code:

  • compliant compilers will print "int", because it was the only definition available at the point of definition of the template and the resolution of foo does not depend on T.
  • VC++ will print "double", because it never bothered with phase 1

It might seem stupid as far as differences go, but if you think about the number of includes you have in a large program, there is a risk that someone will introduce an overload after your template code... and BAM :/

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
  • Any way to get `VC++` to generate a warning at least? This behavior is a nuisance for code that must work across multiple compilers. Developers on our team forget to add the keyword every now and then and the code fails to compile on `Clang` – Samaursa Feb 04 '15 at 23:37
  • 1
    @Samaursa: Unfortunately, not that I know of. If you are using Clang, you may be interesting in knowing that they are developing a drop-in driver for VC++ so you may be able to invoke Clang directly from Visual Studio. – Matthieu M. Feb 05 '15 at 07:22
1

I'm not sure "extension" is exactly how I'd describe VC++ in this respect, but yes, gcc has better conformance in this regard.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • 1
    Isn't this the behavior of Visual Studio in permissive mode? I think that it will reject the code in strict mode, and implements this extension for backwards compatibility with VC6. – MSalters Jun 04 '10 at 15:21