1

インスタンスを識別するためのトレースの自動化については、次のいずれかを呼び出します。

  • その識別子を返す包含オブジェクトの非静的メソッド
  • 常に同じIDを返す何か

私の現在の解決策は、メソッド which() と、オブジェクトのコンテキストにない場合に使用する必要があるグローバル関数 which() を持つ基本クラスを持つことです。ただし、これは静的メンバー関数では機能しません。ここでは、コンパイラはグローバル メソッドよりも非静的メソッドを優先します。

簡単な例:

class IdentBase
{
public:
  Ident(const std::string& id) _id(id) {}
  const std::string& which() const { return _id; }
private:
  const std::string _id;
};

const std::string& which() { static const std::string s("bar"); return s; }

#define ident() std::cout << which() << std::endl

class Identifiable : public IdentBase
{
public:
  Identifiable() : Ident("foo") {}
  void works() { ident(); }
  static void doesnt_work() { ident(); } // problem here
};

静的メンバー関数の特別なマクロのような回避策の使用を回避することはできますか (テンプレート マジックを使用する可能性があります)。

4

3 に答える 3

1

すべての型の既定の識別子を返す関数テンプレートを定義します。

template<typename T>
const std::string& which(const T& object)
{ static const std::string s("bar"); return s; }

関数テンプレートを特定のクラスに特化します。

class IdentBase
{
public:
    IdentBase(const std::string& id): _id(id) {}
    const std::string& id() const { return _id; }
private:
    const std::string _id;
};

template<>
const std::string& which(const IdentBase& object)
{ return object.id(); }

識別したいインスタンスを渡して関数テンプレートを呼び出します。

int main()
{
    int i;
    std::cout << which(i) << std::endl;

    IdentBase foo("foo");
    std::cout << which(foo) << std::endl;

    return 0;
}
于 2009-09-17T17:50:17.383 に答える
0

Boost TypeTraits ライブラリのis_member_function_pointerを使用できる場合があります。ただし、静的なケースと非静的なケースで異なるコードを使用するというsbiの提案はおそらく優れています。

于 2009-09-17T17:45:00.610 に答える
0

あなたの例のように、各クラスのインスタンスごとに異なる識別子が必要ですか、それともトレースにあるクラスを特定しようとしているだけですか?

which() 関数と _id メンバーを static に変更すると、両方が static メンバー関数に公開され、おまけとしてメモリ使用量が減少します。

于 2009-09-17T17:34:44.793 に答える