2012-09-10 221 views
8

我最近花了相当长的一段时间,这段代码调用func()时理解错误消息:奇怪的编译器错误():“成员函数已经定义或声明”,而不是“参考参考”

int main() 
{ 
    vector< vector<double> > v; 

    double sum = 0; 
    for_each(v.begin(), v.end(), 
     bind2nd(ptr_fun(func), &sum)); 

    return 0; 
} 

func()被宣布像这样,代码编译的罚款:

void func(vector<double> v, double *sum) 
{ 
} 

,当我用这个声明(效率),我得到了一个编译器错误:

void func(const vector<double> &v, double *sum) 
{ 
} 

我期望看到的错误是像一个参考 - 参考错误,因为运营商(binder2nd的)的定义,

result_type operator()(const argument_type& _Left) const 

相反,我惊讶的是, Visual C++(VS2012)编译器给我的错误是:

error C2535: 'void std::binder2nd<_Fn2>::operator()(const std::vector<_Ty> &) const' : member function already defined or declared

我不能解密。

  • 你能解释下其机制operator()已经 定义

完整的错误我得到的是:

error C2535: 'void std::binder2nd<_Fn2>::operator()(const std::vector<_Ty> &) const' : member function already defined or declared 
with 
[ 
    _Fn2=std::pointer_to_binary_function<const std::vector<double> &,double *,void,void (__cdecl *)(const std::vector<double> &,double *)>, 
     _Ty=double 
] 
c:\vc\include\xfunctional(319) : see declaration of 'std::binder2nd<_Fn2>::operator()' 
with 
[ 
     _Fn2=std::pointer_to_binary_function<const std::vector<double> &,double *,void,void (__cdecl *)(const std::vector<double> &,double *)> 
] 
c:\consoleapplication1.cpp(31) : see reference to class template instantiation 'std::binder2nd<_Fn2>' being compiled 
with 
[ 
     _Fn2=std::pointer_to_binary_function<const std::vector<double> &,double *,void,void (__cdecl *)(const std::vector<double> &,double *)> 
] 

Build FAILED. 
+3

由于您使用VS 2012,我认为您可以切换到C++ 11并使用lambda/std :: bind来避免这些弃用的东西。 – kennytm

+1

看起来像它指的是binder2nd结构的op(),由于参考折叠(或类似的)被定义了两次相同的签名。 – PlasmaHH

+0

这很有趣。看起来你不能在旧的活页夹包装中使用引用参数类型?! –

回答

6

此行为已定义良好(每个正确的C++编译器都无法编译您的代码)。

从上类模板binder2nd标准(N3376)部分D.9.3operator()这两个defintions存在:

typename Fn::result_type 
operator()(const typename Fn::first_argument_type& x) const; 

typename Fn::result_type 
operator()(typename Fn::first_argument_type& x) const; 

如果first_argument_type已经是const T&,那么他们将是相互矛盾的。

+0

+1,如果'first_argument_type'已经是'T&',那么这似乎就成了一个问题?至少我发现'std :: bind2nd(std :: ptr_fun(f),“xyz”);'如果'f'是'void f(std :: ostream&str,const char * S);'。唉,按值传递'std :: ostream'不是一个选项,所以你似乎必须求助于传递一个指针。 : - / –

0

这不是一个答案,但我只是想记录了现代C++ 11解决方案,其中所有的小帮手绑定在弃用赞成普遍std::bind的:

#include <functional> 
#include <vector> 
#include <algorithm> 

void func(std::vector<double> const & v, double * sum) { /* ... */ } 

int main() 
{ 
    std::vector<std::vector<double>> v; 
    double sum = 0; 
    std::for_each(v.begin(), v.end(), std::bind(func, std::placeholders::_1, &sum)); 
} 

的C++ 11的可变参数模板,以及类型改变性状更全面地收集,给std::bind强得多演绎能力比0以前的组件。