2016-09-15 17 views
2

は、私は、それぞれのクラスのオブジェクトを結合した関数ポインタの数を持っていますそれぞれの 'std :: function'が関連する特定のクラス。バインド解除のstd ::バインド++

auto Unbind(std::function<void()> &Example)->void 
{ 
    //Find which object &Example is bound with (in this case EO/ExampleClass) 
} 

これを行う最善の方法は何ですか?

+3

これはできません。 'std :: function'のターゲットを取得することはできますが、ターゲットタイプは、あなたが後に情報を取得するためのインターフェースを持たない、認識できないタイプのバインド式です。 –

+0

@KerrekSBそれは答えです:) – Quentin

+0

@KerrekSB std :: function :: targetの使用例を教えてください。 –

答えて

4

std::functionは、タイプ消去を実行します。名前ごとに、実際の基になるタイプをインターフェースから消去します。

そこから戻る方法はありません。

あなたがターゲット・オブジェクトのタイプを保持したい場合は、std::mem_fnはあなたが望むものであるかもしれない:

http://en.cppreference.com/w/cpp/utility/functional/mem_fn

+0

'target'はタイプ消去から「帰り道」を提供します。問題は 'std :: bind'です。 –

+0

@KerrekSB target_typeは型ではなく 'std :: type_info'です。したがって、事前に計算された既知のタイプのリストと比較するだけで使用できます。私はそれが意味する意味で(つまり、推測可能な)「帰り道」の資格はないと思います。 –

+1

さて、あなたが期待しているタイプを知る必要がありますが、明確にするために、 'target'(ではなく' target_type')が実際のポインタを返します。実オブジェクト(またはnull)。 –

1

あなたはfunctionオブジェクトとそれを行うことはできません。

可能性は、メソッドとオブジェクトへの参照を格納するラッパーを構築することです。このような

何か:

template<typename T, typename Fn> 
struct MemberFunctionPointer { 
    MemberFunctionPointer(T* ref, Fn fn) : m_ref(ref), 
              m_method(fn) { } 

    template<typename... Args> 
    auto operator()(Args&&... args) { 
    return (m_ref->*m_method)(std::forward<Args...>(args)...); 
    } 

    T* m_ref = nullptr; // a reference (pointer) to the object instance 
    Fn m_method = nullptr; // a reference to the function method 
}; 

注:これはただの傷です。より洗練されたインターフェイスを追加する必要があります。さらに、MemberFunctionPointerオブジェクトを作成するためのヘルパー関数も同様に便利です。

単純にfunctionの代わりにその種のオブジェクトを渡すことができます。

struct Foo { 
    void bar() { 
    // something 
    } 
}; 

int main(int argc, char *argv[]) { 
    Foo f; 
    MemberFunctionPointer<Foo, decltype(&Foo::bar)> method(&f, &Foo::bar); 

    method(); // call the method on the object f. 

    assert(&f == method.get_obj_reference()); 
    return 0; 
} 
関連する問題