c++ - 在 const 成员函数中使用 bind1st

标签 c++ linux stl

ClassA & operator << ( ClassA &, int32_t )
{
    ...
}


class ClassMain
{
public:
    insert( ClassA & c ) const;
    ...
private:
    std::set<int> m_setContainer;
};

struct  InsertOpt : binary_function<ClassA, int, ClassA&>
{
        ClassA & operator( )( ClassA & c, int val ) const
        {
                c << val;
                return c;
        }
};

void ClassMain::insert( ClassA & c ) const
{
    // Case I: the for loop works
    for ( std::set<int>::const_iterator iter = m_setContainer.begin( );
          iter != m_setContainer.end( ); ++iter )
    {
            c << *iter; // operator<<( c, *iter );
    }

    // Case II: doesn't work
    for_each( m_setContainer.begin( ), m_setContainer.end( ), bind1st( InsertOpt(), c ) );


}

Error:
../include/c++/4.1.2/bits/stl_function.h:406: error: no match for call to '(const InsertOpt) (const ClassA&, const int&)'
note: candidates are: ClassA& InsertOpt::operator()(ClassA&, int32_t) const

问题> 为什么编译器寻找 (const ClassA&, const int&) 而不是 ClassA & operator( )( ClassA & c, int val ) const

谢谢

最佳答案

"In general, non-pointer types passed to unary_function or binary_function have consts and references stripped off."

这是不正确的。这意味着对 binary_function 的模板参数应用了一些衰减。 (例如通过 std::decay )。但是标准定义了binary_function在 [depr.base] 中非常明确:

template <class Arg1, class Arg2, class Result>
struct binary_function
{
    typedef Arg1 first_argument_type;
    typedef Arg2 second_argument_type;
    typedef Result result_type;
};

binder1st在[depr.lib.binder.1st]中定义:

template <class Fn>
class binder1st : public unary_function<typename Fn::second_argument_type,
                                        typename Fn::result_type>
{
protected:
    Fn op;
    typename Fn::first_argument_type value;

public:
    binder1st(const Fn& x,
              const typename Fn::first_argument_type& y);

    typename Fn::result_type
    operator()(const typename Fn::second_argument_type& x) const;
    typename Fn::result_type
    operator()(typename Fn::second_argument_type& x) const;
};
  1. The constructor initializes op with x and value with y.

  2. operator() returns op(value,x).

如您所见,存储函数对象的参数是 value , 类型为 typename Fn::first_argument_type . 还要注意如何operator()标记为 const里面。成员(member)value作为 const 传递对象,这会导致您自 InsertOpt 以来的错误消息只接受非 const左值作为第一个参数。

但是,当第一个参数类型作为左值引用给出时,引用折叠规则在访问 value 时适用。通过const访问路径和结果类型 value是“对非常量 ClassA 的左值引用”。

Even when this change, the compiler generates the same error messages.

Compiles for me .

关于c++ - 在 const 成员函数中使用 bind1st,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27067010/

相关文章:

c++ - 在已发布的结构中添加构造函数(在 memcpy 中使用)是否安全?

linux - 如何在 yocto 中为树莓派使用自己的内核配置?

linux - 如何在一行中的 bash 中运行多个后台命令?

c++ - std::function到C样式的函数指针

c++ - 使用 const 后缀自动解析成员函数

c++ - 堆分配的对象可以在堆栈上 move 吗?

c++ - QMessageBox 关闭后 Qt MainWindow 退出

c++ - Bison/Flex 以相反的顺序处理 token

linux -/sys/class/net/<interface>/type值的含义

c++ - std::set<T>::insert,重复元素