2016-07-27 100 views
1

讓我們定義一個結構parser檢查函數指針類型

struct parser { 
    int (*buffer_push_strategy)(); 
    int (*escape_buffer_push_strategy)(); 
    int (*do_callback_strategy)(); 
}; 

我有一個初始化函數:

int parser_init() {  
    if (some_condition) { 
     parser->buffer_push_strategy = buffer_push_strategy1; 
     parser->escape_buffer_push_strategy = escape_buffer_push_strategy1; 
     parser->do_callback_strategy = do_callback_strategy1; 
    } 
    else { 
     parser->buffer_push_strategy = buffer_push_strategy2; 
     parser->escape_buffer_push_strategy = escape_buffer_push_strategy2; 
     parser->do_callback_strategy = do_callback_strategy2; 
    } 
return 0; 
} 

在策略函數定義的地方。好吧,我的興趣在於確定在編寫單元測試時使用了哪種策略。任何想法如何實現?

我在互聯網上看到is_pointer函數C++ 11,但我不認爲這會對我有幫助。

+0

解析器是一個類型,而不是一個變量。在第一段代碼中刪除typedef。 – EFenix

+0

@AntonioGarrido對不起 – astonished

+0

我不確定這個問題...你在找什麼:'int strategy =(parser-> buffer_push_strategy == buffer_push_strategy1)? 1:2;' – EFenix

回答

0

解析器是一個變量:

struct parserT { 
    int (*buffer_push_strategy)(); 
    int (*escape_buffer_push_strategy)(); 
    int (*do_callback_strategy)(); 
} parser; 

如果你想知道哪個策略是,你可以使用:

int strategy= (parser->buffer_push_strategy == buffer_push_strategy1) ? 1 : 2; 

也許,你更喜歡存儲策略號:

int parser_init() {  
    if (some_condition) { 
     parser->buffer_push_strategy = buffer_push_strategy1; 
     parser->escape_buffer_push_strategy = escape_buffer_push_strategy1; 
     parser->do_callback_strategy = do_callback_strategy1; 
     return 1; 
    } 
    else { 
     parser->buffer_push_strategy = buffer_push_strategy2; 
     parser->escape_buffer_push_strategy = escape_buffer_push_strategy2; 
     parser->do_callback_strategy = do_callback_strategy2; 
     return 2; 
    } 
} 

然後,你可以初始化解析器爲:

const int STRATEGY= parser_init(); 
+0

太好了,謝謝! – astonished