プログラミング/C++/C++テクニック のバックアップ(No.1)

更新


公開メモ

概要

C++ は長らく触っていなかったので、 えっ、と思うようなことを知らずに苦労しています。

覚えた内容をここにメモ。

テンプレートクラスの friend

g++ (GCC) 4.3.4 で、

LANG:cpp
template<class T> 
class Test
{
   friend class T;
};

としたところ friend の行で

LANG:console
$ g++ test.cpp
test.cpp:4: error: using template type parameter 'T' after 'class'
test.cpp:4: error: friend declaration does not name a class or function

というエラーが出てしまいました。

どうやらこれは C++ の仕様らしいのだけれど、 以下の様にして回避可能だそうです。

LANG:cpp
template<class T> 
class Test
{
   struct friend_maker { typedef T T2; };
   friend class friend_maker::T2;
};

凄く小手先なんですが・・・

この件について http://www.byte.com/documents/s=9162/cujexp0312wilson2/ に詳しい解説があったようなのですが、今は見られなくなっています。

webarchive 経由で見たところ、http://replay.waybackmachine.org/20041212160407/http://www.byte.com/documents/s=9162/cujexp0312wilson2/

CompilerForm #1Form #2Form #3Form #4
Borland C++ (5.51 & 5.6)Yes
CodeWarrior (7 and 8)YesYesYes
Comeau (4.3.0.1)non-strict onlynon-strict onlynon-strict onlynon-strict only
Digital Mars (8.26-8.37)YesYesYesYes
GCC 2.95Yes
GCC 3.2YesYes
Intel (6 and 7)YesYesYesYes
Visual C++ (4.2 - 7.1)YesYesYes, except 4.2
Watcom (11 and 12)YesYesYes

Counter: 22141 (from 2010/06/03), today: 2, yesterday: 0