Const调用操作符调用绑定的非Const成员函数
const call operator calling bound non-const member function
以下代码在我尝试过的每个编译器(gcc 4.9.2, clang 3.6和VS 2015)上编译良好。然而VS 2013更新4的错误,我将在下面详细说明。这是编译器中的错误吗?
#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成员函数,但修复它没有帮助。
这似乎是一个VS2013编译器的错误,有两种方法来解决它:
使用std::function代替auto来存储对成员函数的调用
std::function<void()> r = std::bind(&Foo::DoFoo, this);
或从Bar
中的函数调用operator()中删除consttemplate<typename Func>
struct Bar
{
Func f_;
Bar(Func f) : f_(f) { }
void operator()() // const
{
f_();
}
};
相关文章:
- 不允许运算符 const 参数调用 const 成员函数
- c++ 是否保证标头初始化的静态 const 成员跨编译单元和库共享单个实例?
- 在类声明中初始化 const 成员变量时在调试模式下出现异常
- 如何避免将 const 和非 const 成员函数输入到模板中的代码重复
- 初始化 const 成员的正确方法
- 使用 Boost 对具有 const 成员的类进行序列化
- 非常量调用 const 成员函数失败,只读位置C++
- PIMPL类的设置应该是const成员函数
- 与其他静态const成员初始化静态常量成员
- decltype 不会推断 const 对象的 const 成员
- 如何初始化不是静态的const成员
- 如何使用常量变量初始化类的 const 成员变量
- 使用模板参数初始化静态 const 成员
- 与const成员配对的向量
- 通过参考const成员通过参考时,尝试引用已删除的函数
- const成员初始化之前的用法是GCC和Clang的这种预期行为
- 通过const成员变量访问内联函数
- 与const成员一起安排新的和班级的分配
- 在const函数中调用非CONST成员的非const函数
- 为什么即使对于 "copy on write" 的 const 成员函数也返回一个代理类?