簡體   English   中英

C ++ 0x和Lambdas

[英]C++0x and lambdas

看一下這個模板:

template <class T>
auto checkErrorCode(T& functor) -> decltype(functor()) {
    auto retCode = functor();
    // ... additional aspect-like stuff with retCode here
    return retCode;
}

它應該執行一個傳遞給它的lambda,從lambda獲取返回值,對其進行處理,然后將其返回給調用方。 考慮“方面編程”,日志記錄等。

即使它可以編譯並可以正常使用...

int foo(int param)
{
    return param>10?0:-1;
}

main()
{
    int param = 11;

    // This compiles fine
    auto action = [&](){ return foo(param); };
    checkErrorCode( action );
}

...它無法編譯-並在我使用內聯lambda直接調用“ checkErrorCode”時發出難以理解的錯誤:

int foo(int param)
{
    return param>10?0:-1;
}

main()
{
    int param = 11;

    // This doesn't compile...
    checkErrorCode( [&](){ return foo(param); } );
}

有什么想法嗎?

g ++發出此奇怪的錯誤:

forSO.cpp: In function 'int main()':
forSO.cpp:24:5: error: no matching function for call to 'checkErrorCode(main()::<lambda()>)'
forSO.cpp:24:5: note: candidate is:
forSO.cpp:2:6: note: decltype (functor()) checkErrorCode(T&) [with T = main()::<lambda()>, decltype (functor()) = int]
forSO.cpp:2:6: note:   no known conversion for argument 1 from 'main()::<lambda()>' to 'main()::<lambda()>&'

在不太可能的情況下,這是編譯器錯誤:

bash$ g++ -v
...
gcc version 4.6.2 (GCC) 

模板需要使用右值引用:

template <class T>
auto checkErrorCode(T&& functor) -> decltype(functor()) {
    auto retCode = functor();
    // ... additional aspect-like stuff with retCode here
    return retCode;
}

或者,const lvalue( const T& )。 由於lambda是臨時(右值)函數,因此只能通過const(左值)引用或右值引用傳遞它們。

通常,除非您打算進行非常量訪問(例如,賦值的左側,非常量成員函數的調用等),否則請保留左值refs const。如果您要進行延續,則它會變得更加復雜,因為那么您必須傳遞一個非常量左值引用。 但是您將擁有一個顯式的函子類,因此允許創建非常量左值引用。 在這種情況下,對於lambdas使用rvalue ref會更清楚,因為const lvalue ref是C ++ 98的處理方式,並且該系統的限制是創建rvalue引用的動力。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM