简体   繁体   中英

Why does this small C++ program not compile using G++?

The following code will not compile with G++ 4.5 or 4.6 (snapshot). It will compile with the Digital Mars Compiler 8.42n.

template <int I>
struct Foo {
  template <int J>
  void bar(int x) {}
};

template <int I>
void test()
{
  Foo<I> a;
  a.bar<8>(9);
};

int main(int argc, char *argv[]) {
  test<0>();
  return 0;
}

The error message is:

bugbody.cpp: In function 'void test() [with int I = 0]':
bugbody.cpp:16:11:   instantiated from here
bugbody.cpp:11:3: error: invalid operands of types '<unresolved overloaded function type>' and 'int' to binary 'operator<'

Is the program valid C++?

Since the bar in a.bar is a dependent name , the compiler doesn't know that it's a template. You need to specify this, otherwise the compiler interprets the subsequent <…> as binary comparison operators:

a.template bar<8>(9);

The compiler behaves correctly.

The reason for this behaviour lies in specialisation. Imagine that you have specialised the Foo class for some value:

template <>
struct Foo<0> {
    int bar;
};

Now your original code would compile, but it would mean something completely different. In the first parsing pass, the compiler doesn't yet know which specialisation of Foo you're using here so it needs to disambiguate between the two possible usages of a.bar ; hence the keyword template to show the compiler that the subsequent <…> are template arguments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM