okuの日記: GCC Bugzilla Bug 19809: template class 内で多重定義される friend 関数
じょ~だんの日記は今日遭遇したバグ経由、Bug 19809 - [4.0/4.1 Regression] Multiple definitions of friend functions in template classes より:
このバグは GCC-4.1.2 で直るとのことですが、正直、こんなコード「あり」なのかと驚きました。 取り敢えず、手元の GCC-(3.3.6|3.4.6|4.0.3|4.1.1) で試してみたサンプルコードは以下のような感じです。
#include <iostream>
extern void foo();
template<int i>
class Foo
{
friend void foo() {
std::cerr << i << std::endl;;
}
};
int main()
{
Foo<1> n1; foo();
Foo<2> n2; foo();
Foo<3> n3; foo();
return 0;
}
GCC-3.3.6 では「再定義」周りのエラーが大量に発生しますが、GCC-(3.4.6|4.0.3|4.1.1) ではすんなりコンパイルが成功して、実行すると「3」と出力します。
Bugzilla のコメントで引用されている、ISO 標準 14.5.3.3 によれば、
3 When a function is defined in a friend function declaration in a class template, the function is defined when the class template is first instantiated. The function is defined even if it is never used.
だそうなので、投稿者の指摘する通り、解は
- 「1」を出力する
- 再定義でエラーになる (投稿者によれば、Comeau の実装はこちら)
のどちらかになるべきなのでしょう。 Bugzilla のコメントによれば、GCC-4.1.2 では、上記のようなプログラムはコンパイルエラーになるようです。
GCC Bugzilla Bug 19809: template class 内で多重定義される friend 関数 More ログイン