コンパイル時にC ++の静的メソッドと非静的メソッドを区別しますか?
-
10-07-2019 - |
質問
インスタンスを識別するためのトレース自動化のために、次のいずれかを呼び出します:
- 識別子を返す包含オブジェクトの非静的メソッド
- 常に同じ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
};
どういうわけか、静的メンバー関数用の特別なマクロのような回避策の使用を回避できますか(テンプレートマジックを使用する場合があります)?
解決
is_member_function_pointer 。ただし、静的および非静的の場合に異なるコードを使用するというsbiの提案の方がおそらく良いでしょう。
他のヒント
すべてのタイプのデフォルト識別子を返す関数テンプレートを定義します。
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;
}
例のように各クラスのすべてのインスタンスに異なる識別子が必要ですか、それともトレースに含まれるクラスを識別しようとしていますか?
which()関数と_idメンバーを静的に変更すると、静的メンバー関数の両方に公開され、ボーナスとしてメモリ使用量が減少します。
所属していません StackOverflow