use*_*370 14 c++ gcc templates g++
以下代码不能使用G ++ 4.5或4.6(快照)进行编译.它将使用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;
}
Run Code Online (Sandbox Code Playgroud)
错误消息是:
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<'
Run Code Online (Sandbox Code Playgroud)
程序是否有效C++?
Kon*_*lph 33
由于barin a.bar是一个从属名称,编译器不知道它是一个模板.您需要指定它,否则编译器会将后续解释<…>为二进制比较运算符:
a.template bar<8>(9);
Run Code Online (Sandbox Code Playgroud)
编译器行为正确.
这种行为的原因在于专业化.想象一下,你已经将这个Foo类专门用于某些价值:
template <>
struct Foo<0> {
int bar;
};
Run Code Online (Sandbox Code Playgroud)
现在你的原始代码会编译,但这意味着完全不同的东西.在第一个解析过程中,编译器还不知道Foo你在这里使用了哪个特化,所以它需要消除两个可能的用法之间的歧义a.bar; 因此关键字template向编译器显示后续<…>是模板参数.