0

メンバ関数ポインタを外部関数に渡し、次にメンバ関数(Do not ask!)によって再度呼び出される、ちょっと複雑な使用例があります。私はstd::functionstd::mem_fnについて学んだが、私は私の古い学校の関数ポインタを変換することができるように見えることはできません以下のコードでstd::function<void (T::*)(int) func>メンバ関数へのポインタをstd :: functionに変換する

void (T::*func)(int)、私が合格できるようにしたいと思いますanotherMember

#include "class2.hpp" 
#include <iostream> 

class outer{ 
public: 
    void aMember(int a){ 
    std::cout << a <<std::endl; 
    } 
    void anotherMember(double){ 
    memFuncTaker(this, &outer::aMember); 
    } 

}; 


template<class T> 
void memFuncTaker(T* obj , void (T::*func)(int)){ 
    (obj->*func)(7); 
} 
+6

あなたのコードで 'std :: function'を使う試みはありません。 – AnT

+0

あなたの質問タイトルは "std :: functionへのポインタをメンバー関数に変換する"と言いますが、 "std :: functionをメンバ関数へのポインタに変換する"のように聞こえます。 –

答えて

1

からの呼び出しでmemFuncTakerへのstd ::機能あなたは非静的メンバ関数ポインタにstd::functionをバインドすると、それはそれ解像度の最初の明示的なパラメータ作り、隠されたthisパラメータを「明らかに」究極のファンクタ。あなたが好むのであればouter::aMemberためのあなたのケースでは、あなたがstd::function<void(outer *, int)>を使用したいと2パラメータファンクタもちろん

#include <functional> 
#include <iostream> 

template<class T> 
void memFuncTaker(T *obj , std::function<void(T *, int)> func){ 
    func(obj, 7); 
} 

class outer{ 
public: 
    void aMember(int a){ 
    std::cout << a <<std::endl; 
    } 
    void anotherMember(double){ 
    memFuncTaker(this, std::function<void(outer *, int)>{&outer::aMember}); 
    } 
}; 

int main() { 
    outer o; 
    o.anotherMember(0); 
} 

http://coliru.stacked-crooked.com/a/5e9d2486c4c45138

で終わる、あなたがによって(そのファンクタの最初の引数をバインドすることができます従ってstd::bind又はラムダ)を使用して、このバージョンでmemFuncTakerがもはやの主要目的の一つであることを起こるテンプレートを(なければならないこと

#include <functional> 
#include <iostream> 

using namespace std::placeholders; 

void memFuncTaker(std::function<void(int)> func){ 
    func(7); 
} 

class outer{ 
public: 
    void aMember(int a){ 
    std::cout << a <<std::endl; 
    } 
    void anotherMember(double){ 
    memFuncTaker(std::function<void(int)>(std::bind(&outer::aMember, this, _1))); 
    } 
}; 

int main() { 
    outer o; 
    o.anotherMember(0); 
} 

注再び「隠していません」- コードを「テンプレート解除する」ためにタイプ消去技術を使用します)。

+0

'std :: bind(&outer :: aMember、this、_1)の戻り値の型は' std :: function 'です。私は 'aMember'がメンバ関数だと知っていますが、' this'は 'std :: function'にバインドされた関数シグネチャを表示しません。私は 'std :: function ' – creationist

+0

を返すために 'std :: bind(&outer :: aMember、this、_1)'を期待していました。その 'std :: bind'の目的は、最初の(' outer * ')パラメータを取り除く(バインドする)ことです。 * * 'std :: bind'の前に、ファンクタは' outer * 'と' int'の2つのパラメータを持っていましたが、 '* std :: bind'の後に' int'が残っていました。 – AnT

+0

別の例として、 'std :: mem_fn(&outer :: aMember)'を実行すると、2つのパラメータを持つfunctiorが得られます。しかし、その後で 'std :: bind(std :: mem_fn(&outer :: aMember)、this、_1)'を実行すると、1つのパラメータだけが残されます。上の答えで見られるのは同じことです。なぜなら 'std :: mem_fn'はこの文脈ではオプションであり省略することができるからです。 'std :: bind'は、' std :: mem_fn'の明示的な適用なしに何が意味されているかを理解するのに十分スマートです。 – AnT

関連する問題