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; };
The constructor initializes
op
withx
and value withy
.
operator()
returnsop(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.
关于c++ - 在 const 成员函数中使用 bind1st,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27067010/