C++ 对通过引用获取参数的方法使用bind1st
我有一个这样的结构:C++ 对通过引用获取参数的方法使用bind1st,c++,visual-c++,C++,Visual C++,我有一个这样的结构: struct A { void i(int i) {} void s(string const &s) {} }; 现在,当我尝试这个: bind1st(mem_fun(&A::i), &a)(0); bind1st(mem_fun(&A::s), &a)(""); 第一行编译为OK,但第二行生成错误: c:\program files (x86)\microsoft visual studio 10.0\vc\i
struct A {
void i(int i) {}
void s(string const &s) {}
};
现在,当我尝试这个:
bind1st(mem_fun(&A::i), &a)(0);
bind1st(mem_fun(&A::s), &a)("");
第一行编译为OK,但第二行生成错误:
c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional(299): error C2535: 'void std::binder1st<_Fn2>::operator ()(const std::basic_string<_Elem,_Traits,_Ax> &) const' : member function already defined or declared
with
[
_Fn2=std::mem_fun1_t<void,A,const std::string &>,
_Elem=char,
_Traits=std::char_traits<char>,
_Ax=std::allocator<char>
]
c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional(293) : see declaration of 'std::binder1st<_Fn2>::operator ()'
with
[
_Fn2=std::mem_fun1_t<void,A,const std::string &>
]
c:\work\sources\exception\test\exception\main.cpp(33) : see reference to class template instantiation 'std::binder1st<_Fn2>' being compiled
with
[
_Fn2=std::mem_fun1_t<void,A,const std::string &>
]
c:\ProgramFiles(x86)\microsoft visual studio 10.0\vc\include\xFunction(299):错误C2535:“void std::binder1st::operator()(const std::basic_string&)const”:成员函数已定义或声明
具有
[
_Fn2=std::mem\u fun1\t,
_Elem=char,
_Traits=std::char\u Traits,
_Ax=std::分配器
]
c:\ProgramFiles(x86)\microsoft visual studio 10.0\vc\include\xFunction(293):请参见“std::binder1st::operator()”的声明
具有
[
_Fn2=std::mem\u fun1\t
]
c:\work\sources\exception\test\exception\main.cpp(33):请参阅正在编译的类模板实例化'std::binder1st'的参考
具有
[
_Fn2=std::mem\u fun1\t
]
有什么问题吗?我怎样才能修好它
编辑:
似乎任何参考论点都是一个问题。因此,如果我将
I
方法更改为void I(int&I){}
我会得到一个类似的错误。这个问题是库规范中的一个缺陷
查看此针对gcc的错误报告以及由此产生的讨论:
C++03缺乏构建完美绑定库的工具。这个问题在C++11中通过完美转发和std::bind得到了解决。std::bind1st和std::bind2nd不接受带有引用参数的函子,因为它们本身构成了对这些参数的引用。你可以
正如您已经假设的,对std::string的引用就是问题所在。它不是有效的模板参数。通过指针更改引用
#include <functional>
#include <string>
struct A {
void i(int i) {}
void s(const std::string *s) {}
};
int main(void)
{
A a;
std::bind1st(std::mem_fun(&A::i), &a)(0);
const std::string s("");
std::bind1st(std::mem_fun(&A::s), &a)(&s);
}
#包括
#包括
结构A{
void i(int i){}
void s(const std::string*s){}
};
内部主(空)
{
A A;
std::bind1st(std::mem_-fun(&A::i)和&A)(0);
常量std::字符串s(“”);
std::bind1st(std::mem_-fun(&A::s)和&A::s);
}
考虑到我们在2011年拥有C++11,您可能想看看C++11sstd::bind
或boost::bind
,它们使这些事情更容易处理。@Plasmah:不幸的是,我不能在这个项目中使用C++11。虽然这是事实,函数的参数类型通过第一个参数类型typedef从mem_fun传输到bind1st,引用是有效的typedef。因此std::bind1st理论上可以接受引用,但实现方式不同(此实现是由标准IIRC强制执行的)。