c++ - 使用 bind2nd() : "member function already defined or declared" instead of "reference to reference" 的奇怪编译器错误

标签 c++ templates compiler-errors bind2nd

我最近花了很多时间来理解在这段代码中调用 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 )
{
}

我期望看到的错误类似于 reference-to-reference 错误,因为 binder2nd 的 operator() 的定义,

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.

最佳答案

这种行为是明确定义的(每个正确的 C++ 编译器都无法编译您的代码)。

在类模板 binder2nd 的标准 (N3376) 部分 D.9.3 中,存在 operator() 的这两个定义:

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&,那么它们就会发生冲突。

关于c++ - 使用 bind2nd() : "member function already defined or declared" instead of "reference to reference" 的奇怪编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12349677/

相关文章:

c++ - .h 文件中的字符串预定义并使用它来过滤用户输入

c++ - 密码无效

xcode - Parse.com 入门项目在 xcode 6.3 上出现 Cannot invoke 'subscribeToChannelInBackground' 编译器错误

C++ lambda 函数访问写冲突

c++ - 如何处理 .dump/.dump 文件?

python - 读取管道(C/C++),没有错误,但不是所有数据

c - 头文件被包含两次

C++模板静态类代码生成

html - 如何在 Golang 中设置 HTML <select> 元素的默认值?

c++ - 这段代码是什么意思?