2013-11-22 53 views
2

最後的線下不會在Visual Studio 2005中編譯:lambda表達式替換 - Boost庫

std::deque<int> q; 
boost::condition_variable cond; 
boost::mutex mu; 
boost::unique_lock<boost::mutex> locker(mu); 
cond.wait(locker, [](){ return !q.empty();}); // Unlock mu and wait to be notified 

我認爲這是一個lambda表達式,我懷疑的是,Visual Studio 2005的編譯器不支持語法... C++ 11?無論如何,除了更改我的編譯器之外,我可以解決這個問題嗎?

下面是來自升壓類聲明:

class condition_variable: 
    private detail::basic_condition_variable 
{ 
public: 
    BOOST_THREAD_NO_COPYABLE(condition_variable) 
    condition_variable() 
    {} 

    using detail::basic_condition_variable::notify_one; 
    using detail::basic_condition_variable::notify_all; 

    void wait(unique_lock<mutex>& m) 
    { 
     do_wait(m,detail::timeout::sentinel()); 
    } 

    template<typename predicate_type> 
    void wait(unique_lock<mutex>& m,predicate_type pred) 
    { 
     while(!pred()) wait(m); 
    } 

...

編譯器輸出:

error C2059: syntax error : '[' 
error C2143: syntax error : missing ')' before '{' 
error C2143: syntax error : missing ';' before '{' 
+0

Boost有Boost.Lambda和Boost.Phoenix的lambda。 – chris

+0

@chris:但是編譯器不支持語法嗎?如果不是,我應該包含哪些Boost標題來編譯上面的代碼? –

+0

不,它沒有。這是它的美麗。 Boost使用C++ 03做了一些非常棒的事情。無論如何,去看看文檔(和教程)。這包括標題。 – chris

回答

2
class UntilEmpty 
{ 
public: 
    UntilEmpty(std::deque<int>& t) : q(t) {} 

    bool operator()() { return !q.empty(); } 

private: 
    std::deque<int>& q; 
}; 

然後簡單地使用:

UntilEmpty until_empty(q); 
cond.wait(locker, until_empty); 

順便說一下,UntilEmpty通常被稱爲函子。

+0

對不起,我不小心省略了隊列的聲明。我編輯了我原來的問題來添加它。 –

+0

您的解決方案如上所述。仍然對通過Chris的建議添加lambda支持感興趣,但它比簡單地添加boost頭文件更復雜:#include「boost \ lambda \ lambda.hpp」和 #include「boost \ phoenix \ phoenix.hpp」。我會按照他的建議查看lambda教程。 –