私の同僚は、彼がチームで使用した小さなデザインについて話してくれました。これは、非常に分離された方法で特化できる一種の特性クラスです。
それがどのように機能するのかを理解するのに苦労しました。また、自分のアイデアがまだよくわからないので、ここで助けを求めようと思いました.
ここでは g++、具体的にはバージョン 3.4.2 と 4.3.2 (両方で動作するようです) について話しています。
アイデアは非常に単純です。
1- インターフェイスを定義する
// interface.h
template <class T>
struct Interface
{
void foo(); // the method is not implemented, it could not work if it was
};
//
// I do not think it is necessary
// but they prefer free-standing methods with templates
// because of the automatic argument deduction
//
template <class T>
void foo(Interface<T>& interface) { interface.foo(); }
2-クラスを定義し、ソースファイルでこのクラスのインターフェースを特殊化します(そのメソッドを定義します)
// special.h
class Special {};
// special.cpp
#include "interface.h"
#include "special.h"
//
// Note that this specialization is not visible outside of this translation unit
//
template <>
struct Interface<Special>
{
void foo() { std::cout << "Special" << std::endl; }
};
3- 使い方も簡単です:
// main.cpp
#include "interface.h"
class Special; // yes, it only costs a forward declaration
// which helps much in term of dependencies
int main(int argc, char* argv[])
{
Interface<Special> special;
foo(special);
return 0;
};
Interface
forの特殊化を定義した翻訳単位がない場合、これは未定義のシンボルですSpecial
。
さて、これにはキーワードが必要だと思っていたでしょうがexport
、これは私の知る限り、g ++で実装されたことはありません(C ++コンパイラで実装されたのは1回だけで、作成者は時間と労力を考えるとそうしないようにアドバイスしています)。
テンプレートメソッドを解決するリンカーと関係があると思われます...
- このようなものに会ったことがありますか?
- それは標準に準拠していますか、それともうまくいくのは幸運な偶然だと思いますか?
私はその構成にかなり戸惑っていることを認めなければなりません...