Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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++?

like image 944
user2023370 Avatar asked May 04 '11 10:05

user2023370


People also ask

Can you use G++ to compile C?

G++ is the name of the compiler. (Note: G++ also compiles C++ code, but since C is directly compatible with C++, so we can use it.).

What does G do in compiling?

The -g option instructs the compiler to generate debugging information during compilation. In C++, the -g option turns on debugging and turns off inlining of functions. The- g0 (zero) option turns on debugging and does not affect inlining of functions.


1 Answers

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.

like image 166
Konrad Rudolph Avatar answered Nov 15 '22 14:11

Konrad Rudolph