2011-02-25 46 views
3
typedef solution_type (*algorithm_ptr_type) (
    problem_type problem, 
    void (*post_evaluation_callback)(void *move, int score)/* = NULL*/ 
); 

請幫幫我!謝謝找出模糊指針typedef

+7

這意味着有人認爲編寫不可維護的代碼行很有趣。 – 2011-02-25 05:54:18

+5

我聽說[careers.stackoverflow.com](http://careers.stackoverflow.com/)剛剛升級。如果你被要求維護這樣的代碼,也許值得考慮一下...... – 2011-02-25 05:56:36

+1

它是C還是C++?他們不是一回事 – 2011-02-25 06:02:16

回答

16

這意味着,algorithm_ptr_type是一個指向返回solution_type的功能和它的參數是:類型

  • post_evaluation_callback

    • 問題這又是一個函數指針接受兩個參數(void*int),並返回void

    而且同樣可以寫成(簡單,易讀的語法):

    typedef void (*callback_type)(void *move, int score); 
    
    typedef solution_type (*algorithm_type)(problem_type, callback_type); 
    

    注:參數的名稱是可選的,所以我刪除它,使typedef簡短而可愛!的

    using algorithm_ptr_type = solution_type (*) (
        problem_type, 
        void(*)(void*, int) 
    );  
    

    也就是說要好得多,因爲現在很明顯,以什麼被定義和術語:


    在C++ 11,這可以進一步簡化如下什麼


    在C++ 11,甚至可以定義一個實用程序來創建函數指針,

    //first define a utility to make function pointer. 
    template<typename Return, typename ... Parameters> 
    using make_fn = Return (*)(Paramaters...); 
    

    然後用它作爲,

    using callback_type = make_fn<void, void*, int>; 
    
    using algorithm_type = make_fn<solution_type, problem_type, callback_type>; 
    

    這裏的第一個參數make_fn是返回類型,其餘都是參數—容易破譯每一個!


    用法:

    solution_type SomeFunction(problem_type problem, callback post_evaluation) 
    { 
        //implementation 
    
        //call the callback function 
        post_evaluation(arg1, arg2); 
        //.. 
    } 
    
    algorithm_ptr_type function = SomeFunction; 
    
    //call the function 
    function(arg, someOtherFunction); 
    
  • +0

    謝謝,但那個函數的名字是什麼? – 2011-02-25 05:59:35

    +2

    在代碼中沒有函數:有一個函數指針類型(名爲'algorithm_ptr_type')和一個指向函數的指針(名爲'post_evaluation_callback')。 – 2011-02-25 06:01:40

    +0

    @Andy:我解釋了這個用法。請看看! – Nawaz 2011-02-25 06:11:51

    1

    定義solution_type作爲函數指針給帶有problem_type和另一個函數指針的函數。這第二個函數指針接受一個void *(任何)和一個int作爲參數。

    +2

    實際上,solution_type是返回類型,而不是函數指針。 – Marlon 2011-02-25 06:17:21

    5

    這是多麼可怕的一段代碼!

    它所做的是定義一個稱爲algorithm_ptr_type的函數指針類型,返回solution_type並將作爲其第一個參數並將回調作爲其第二個參數。該回調需要void*int作爲其參數並且不返回任何內容。

    一個更好的方式來寫,這將是:

    typedef void (*post_evaluation_callback)(void *move, int score); 
    typedef solution_type (*algorithm_ptr_type)(problem_type problem, post_evaluation_callback callback); 
    
    +0

    'post_evaluation_callback'不返回'solution_type'。它返回'void' ....'algorithm_ptr_type'返回'solution_type'。 – Nawaz 2011-02-25 06:30:54

    +0

    @Nawaz:很對,在那裏複製並粘貼錯誤:P – Necrolis 2011-02-25 08:00:57

    2

    這令人沮喪的一段代碼,使得它使algorithm_ptr_type是一個函數指針。

    此類型必須指向一個返回類型爲solution_type的對象的函數。
    此類型必須指向一個採用以下參數的函數:
    0:類型爲problem_type的對象。
    1:函數指針必須指向一個函數: 返回void。
    請注意以下參數:
    0:A void*
    1:一個int