weird compiler error using bind2nd(): “member function already defined or declared” instead of “reference to reference”

前端 未结 2 596
野的像风
野的像风 2021-01-12 05:22

I recently spent quite some time understanding the error message when calling func() in this piece of code:

int main()
{
    vector< vector&l         


        
相关标签:
2条回答
  • 2021-01-12 06:06

    This behavior is well-defined (every correct C++ compiler will fail to compile your code).

    From the standard (N3376) section D.9.3 on class template binder2nd, these two defintions of operator() exist:

    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;
    

    If first_argument_type is already a const T&, then they will be conflicting.

    0 讨论(0)
  • 2021-01-12 06:26

    This isn't an answer, but I just want to record the modern C++11 solution, where all the small bind helpers are deprecated in favour of the universal 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));
    }
    

    The variadic templates of C++11, as well as a more comprehensive collection of type-modifying traits, give std::bind much stronger deduction abilities than the previous components in <functional>.

    0 讨论(0)
提交回复
热议问题