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++?
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.).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With