问题描述
以下代码在我尝试过的每个编译器(gcc 4.9.2,clang 3.6和VS 2015)上均可正常编译.但是VS 2013更新4消除了错误,我将在下面详细介绍.这是编译器中的错误吗?
The following code compiles fine on every compiler I tried (gcc 4.9.2, clang 3.6 and VS 2015). However VS 2013 update 4 craps out with the error I will detail below. Is this a bug in the compiler?
#include <iostream>
#include <functional>
template<typename Func>
struct Bar
{
Func f_;
Bar(Func f) : f_(f) { }
void operator()() const
{
f_();
}
};
template<typename T>
void Baz(T const& t)
{
Bar<T> b(t);
b();
}
struct Foo
{
Foo()
{
auto r = std::bind(&Foo::DoFoo, this);
Baz(r);
}
void DoFoo() { std::cout << "Doing Foo!\n"; }
};
int main()
{
Foo f;
return 0;
}
错误列表如下:
1>doodle.cpp(15): error C3848: expression having type 'const std::_Bind<true,void,std::_Pmf_wrap<void (__thiscall Foo::* )(void),void,Foo,>,Foo *const >' would lose some const-volatile qualifiers in order to call 'void std::_Bind<true,void,std::_Pmf_wrap<void (__thiscall Foo::* )(void),void,Foo,>,Foo *const >::operator ()<>(void)'
1> doodle.cpp(14) : while compiling class template member function 'void Bar<T>::operator ()(void) const'
1> with
1> [
1> T=std::_Bind<true,void,std::_Pmf_wrap<void (__thiscall Foo::* )(void),void,Foo,>,Foo *const >
1> ]
1> doodle.cpp(23) : see reference to function template instantiation 'void Bar<T>::operator ()(void) const' being compiled
1> with
1> [
1> T=std::_Bind<true,void,std::_Pmf_wrap<void (__thiscall Foo::* )(void),void,Foo,>,Foo *const >
1> ]
1> doodle.cpp(22) : see reference to class template instantiation 'Bar<T>' being compiled
1> with
1> [
1> T=std::_Bind<true,void,std::_Pmf_wrap<void (__thiscall Foo::* )(void),void,Foo,>,Foo *const >
1> ]
1> doodle.cpp(31) : see reference to function template instantiation 'void Baz<std::_Bind<true,void,std::_Pmf_wrap<void (__thiscall Foo::* )(void),void,Foo,>,Foo *const >>(const T &)' being compiled
1> with
1> [
1> T=std::_Bind<true,void,std::_Pmf_wrap<void (__thiscall Foo::* )(void),void,Foo,>,Foo *const >
1> ]
我以为它希望DoFoo()是一个const成员函数,但是修复它并没有帮助.
I thought it wanted DoFoo() to be a const member function but fixing that didn't help.
推荐答案
这似乎是VS2013编译器错误,有2种解决方法:
This seems to be a VS2013 compiler bug and there are 2 ways to work around it:
使用std :: function而不是auto来存储对成员函数的调用
Use std::function instead of auto to store a call to a member function
std::function<void()> r = std::bind(&Foo::DoFoo, this);
或从Bar中的函数调用operator()中删除const
Or remove const from function call operator() in Bar
template<typename Func>
struct Bar
{
Func f_;
Bar(Func f) : f_(f) { }
void operator()() // const
{
f_();
}
};
这篇关于const调用运算符,调用绑定的非const成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!