2013-10-09 43 views
2

我有這樣的事情:null實現類型爲boost ::功能

boost::function<void(void)> redStyle = boost::bind(colorStyle, "red"); 

boost::function<void(void)> blueBlinkingStyle = boost::bind(animatedStyle, "blue", BLINKING); 

這是正確的方式來定義一個nullStyler:

void nothing(){} 
boost::function<void(void)> noStyle = boost::bind(nothing); 

我在想,我能做到這方式代替,但空函數拋出:

boost::function<void(void)> noStyle; 

使用造型器功能,可以檢查空,而不是使用的代碼「空對象模式「。哪個更好?在我的Detail命名空間中有一個奇怪的沒有功能或檢查空?

回答

3

我寧願有一個無操作功能。它清楚地表達了它的意圖,它可以幫助您避免檢查仿函數是否爲空(假設您不需要因其他原因而停止工作)。

請注意,您不需要調用綁定。你可以這樣做:

boost::function<void(void)> noStyle = nothing; 

例子:

#include <boost/function.hpp> 
#include <iostream> 

void hello() 
{ 
    std::cout << "hello" << std::endl; 
} 

int main() 
{ 
    boost::function<void(void)> f = hello; 
    f(); 
} 
+0

或者。 'std :: function noStyle = [] {};'...這要求你輸入3個字符少。 – Nawaz

+0

@Nawaz的好處,雖然我總是假設一個人沒有C++ 11支持時使用'boost :: function'。 – juanchopanza

+1

@Angew我明顯考慮到整個「C++ 11是C++」的東西有點太:) – juanchopanza