[問題] functor to function pointer

看板C_and_CPP作者 (沒有靈感..)時間9年前 (2015/04/29 12:06), 編輯推噓2(2018)
留言20則, 5人參與, 最新討論串1/2 (看更多)
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) MSVC++ 10.0 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) std 問題(Question): runtime error 餵入的資料(Input): 預期的正確結果(Expected Output): print 1 2 3 錯誤結果(Wrong Output): access violation 程式碼(Code):(請善用置底文網頁, 記得排版) http://ideone.com/1FKquB 補充說明(Supplement): 如程式碼,會死在18行 fp g3 = *g1.target<fp>(); 請問應該要怎麼寫才是正確的 -- -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 203.69.170.37 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1430280373.A.BC0.html

04/29 12:17, , 1F
基本上沒辦法把std::bind回傳的東西轉成func. pointer
04/29 12:17, 1F

04/29 12:17, , 2F
頂多就 g1.target<decltype(std::bind(f, _1))>() 吧
04/29 12:17, 2F

04/29 12:18, , 3F
好奇你幹麻不就直接用g1 = f建構就好
04/29 12:18, 3F

04/29 12:24, , 4F
其實我想做的事是bind一個member function
04/29 12:24, 4F

04/29 12:24, , 5F
然後傳給一個function pointer
04/29 12:24, 5F

04/29 13:02, , 6F
基本上function pointer是沒有state的
04/29 13:02, 6F

04/29 13:02, , 7F
當然如果你可以多傳一個this的話可以參考:
04/29 13:02, 7F

04/29 13:02, , 8F

04/29 15:28, , 9F
bind 出來應該會是某種 anonymous type?
04/29 15:28, 9F

04/29 15:28, , 10F
就像每個 lambda 的 type 都不一樣
04/29 15:28, 10F

04/29 15:29, , 11F
我覺得可以直接傳 std::function 的話是最簡單的辦法
04/29 15:29, 11F

04/29 15:35, , 12F
因為我要call的API是function pointer
04/29 15:35, 12F

04/29 15:37, , 13F
所以想從std::function bind一個member function傳過去
04/29 15:37, 13F

04/29 17:29, , 14F
如果你使用一個設計良好的API,在傳入callback時
04/29 17:29, 14F

04/29 17:29, , 15F
應該還可以傳入一個void*作為額外參數
04/29 17:29, 15F

04/29 17:30, , 16F
而API會把這個void*當參數去呼叫你的function pointer
04/29 17:30, 16F

04/29 17:31, , 17F
這麼一來你就可以傳遞this pointer了
04/29 17:31, 17F

04/29 17:32, , 18F
只是,並非所有的API設計者都有這種sense :(
04/29 17:32, 18F

04/29 17:44, , 19F
可惜沒有多一個參數 我也無法去修改那個API :(
04/29 17:44, 19F

04/29 18:01, , 20F
另一種可能就是用 template 生 wrapper 去被指
04/29 18:01, 20F
文章代碼(AID): #1LG5Yrl0 (C_and_CPP)
文章代碼(AID): #1LG5Yrl0 (C_and_CPP)