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 compil开发者_StackOverflow社区e 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.
精彩评论