2013-03-25 28 views
3

這裏的std :: NOT1編譯是我的代碼:誤差時unary_function使用引用參數

using namespace std; 

class Pixel 
{ 
public: 
    bool AreSamplesIdentical() const 
    { 
     return true; 
    } 
}; 

namespace 
{ 
class Predicate_SamplesEqual : public unary_function<const Pixel&, bool> 
{ 
public: 
    bool operator() (const Pixel& pixel) const 
    { 
     return pixel.AreSamplesIdentical(); 
    } 
}; 
} 

int main() 
{ 
    vector<Pixel> pixels(10); 
    find_if(pixels.begin(), pixels.end(), not1(Predicate_SamplesEqual())); 
} 

在Visual Studio 2008中C++ Express中,我得到錯誤: 錯誤C2529: '_Left':參考參考非法 從庫內部代碼。

但我想在這裏和它編譯: http://ideone.com/swWrZT

誰是錯在這裏?如果我,我如何編碼解決方法?

錯誤發生時所指示的線從官能

// TEMPLATE CLASS unary_negate 
template<class _Fn1> 
    class unary_negate 
    : public unary_function<typename _Fn1::argument_type, bool> 
    { // functor adapter !_Func(left) 
public: 
    explicit unary_negate(const _Fn1& _Func) 
     : _Functor(_Func) 
     { // construct from functor 
     } 

    /**error**/bool operator()(const typename _Fn1::argument_type& _Left) const 
     { // apply functor to operand 
     return (!_Functor(_Left)); 
     } 

protected: 
    _Fn1 _Functor; // the functor to apply 
    }; 
+0

請告訴我完整的錯誤,特別是你的代碼的行使得報錯了? – PlasmaHH 2013-03-25 16:50:56

+0

編輯包含。 – 2013-03-25 16:56:30

回答

1

Who is wrong here?

既不MSVC也不GCC要求時使用默認選項運行,以符合任何標準,因此既不是完全「錯誤」。

在這種情況下,GCC 4.7應用了C++ 11參考摺疊規則(即使沒有C++ 11模式也是GNU擴展)。

如果您希望GCC符合先前的標準,請傳遞命令行選項--std=c++98,它會拒絕您的代碼。

+0

謝謝!你知道我可以如何解決這個問題嗎?我編輯了我的問題。 – 2013-03-25 17:06:03

+0

@Neil:maverik的解決方法是正確的,當'operator()'實際上需要'T const&'時,允許'argument_type'爲'T'。參見例如'std :: negate'。 – 2013-03-25 17:17:16

+0

你爲什麼被允許? – 2013-03-25 17:46:27

4

我想這錯誤是由於unary_function使用第一個模板參數的類型,使一個參考:

template<typename Arg, typename Result> 
struct unary_function 
{ 
    typedef Arg argument_type; 
    typedef Result result_type; 
    ... 
    virtual result_type operator()(const argument_type& _Left) const = 0; 
    ... 
} 

所以,如果Argconst X&然後operator()使用const X& & - 引用來引用和VC 9.0無法處理它。

最明顯的解決方法是這樣寫:

class Predicate_SamplesEqual : public unary_function<Pixel, bool> 
...